diff --git a/frontend/src/app/app.component.spec.ts b/frontend/src/app/app.component.spec.ts index 3b9d2ecb7..4a063a04b 100644 --- a/frontend/src/app/app.component.spec.ts +++ b/frontend/src/app/app.component.spec.ts @@ -8,6 +8,7 @@ import { AppComponent } from "./app.component"; import { AuthInitializationService } from "./core/security/auth-initialization-service"; import { RxStompService } from "./shared/websocket/rx-stomp.service"; import { BookService } from "./features/book/service/book.service"; +import { MetadataRefreshSubmissionService } from "./features/metadata/data/metadata-refresh-submission.service"; import { NotificationEventService } from "./shared/websocket/notification-event.service"; import { AppThemeService } from "./shared/service/app-theme.service"; import { MetadataProgressService } from "./shared/service/metadata-progress.service"; @@ -48,6 +49,7 @@ describe("AppComponent", () => { }; let bookdropFileService: { handleIncomingFile: ReturnType }; let taskService: { handleTaskProgress: ReturnType }; + let metadataRefreshSubmissionService: { handleBatchProgress: ReturnType }; let libraryHealthService: { initWebsocket: ReturnType, fetchHealth: ReturnType }; let authService: { forceLogout: ReturnType, isAuthenticated: ReturnType }; let libraryImportProgressService: { recordBookAdded: ReturnType }; @@ -89,6 +91,7 @@ describe("AppComponent", () => { metadataProgressService = { handleIncomingProgress: vi.fn() }; bookdropFileService = { handleIncomingFile: vi.fn() }; taskService = { handleTaskProgress: vi.fn() }; + metadataRefreshSubmissionService = { handleBatchProgress: vi.fn() }; libraryHealthService = { initWebsocket: vi.fn(), fetchHealth: vi.fn() }; authService = { forceLogout: vi.fn(), isAuthenticated: signal(auth.authenticated) }; libraryImportProgressService = { recordBookAdded: vi.fn() }; @@ -121,6 +124,7 @@ describe("AppComponent", () => { { provide: MetadataProgressService, useValue: metadataProgressService }, { provide: BookdropFileService, useValue: bookdropFileService }, { provide: TaskService, useValue: taskService }, + { provide: MetadataRefreshSubmissionService, useValue: metadataRefreshSubmissionService }, { provide: LibraryHealthService, useValue: libraryHealthService }, { provide: AuthService, useValue: authService }, { provide: LibraryImportProgressService, useValue: libraryImportProgressService }, @@ -216,6 +220,9 @@ describe("AppComponent", () => { expect(metadataProgressService.handleIncomingProgress).toHaveBeenCalledWith( { taskId: "task-1" }, ); + expect(metadataRefreshSubmissionService.handleBatchProgress).toHaveBeenCalledWith( + { taskId: "task-1" }, + ); expect(notificationEventService.handleNewNotification).toHaveBeenCalledWith( { message: "info", diff --git a/frontend/src/app/app.component.ts b/frontend/src/app/app.component.ts index 8d57ece60..fcf516e1b 100644 --- a/frontend/src/app/app.component.ts +++ b/frontend/src/app/app.component.ts @@ -20,6 +20,7 @@ import {CommandPaletteComponent} from './features/command-palette/command-palett import {CommandPaletteService} from './features/command-palette/command-palette.service'; import {LibraryImportProgressService} from './shared/service/library-import-progress.service'; import {AuthorService} from './features/author-browser/service/author.service'; +import {MetadataRefreshSubmissionService} from './features/metadata/data/metadata-refresh-submission.service'; @Component({ selector: 'app-root', @@ -44,6 +45,7 @@ export class AppComponent implements OnInit, OnDestroy { private metadataProgressService = inject(MetadataProgressService); private bookdropFileService = inject(BookdropFileService); private taskService = inject(TaskService); + private metadataRefreshSubmissionService = inject(MetadataRefreshSubmissionService); private libraryHealthService = inject(LibraryHealthService); private authService = inject(AuthService); private commandPaletteService = inject(CommandPaletteService); @@ -140,9 +142,11 @@ export class AppComponent implements OnInit, OnDestroy { ) ); this.subscriptions.push( - this.rxStompService.watch('/user/queue/book-metadata-batch-progress').subscribe(msg => - this.metadataProgressService.handleIncomingProgress(JSON.parse(msg.body) as MetadataBatchProgressNotification) - ) + this.rxStompService.watch('/user/queue/book-metadata-batch-progress').subscribe(msg => { + const progress = JSON.parse(msg.body) as MetadataBatchProgressNotification; + this.metadataProgressService.handleIncomingProgress(progress); + this.metadataRefreshSubmissionService.handleBatchProgress(progress); + }) ); this.subscriptions.push( this.rxStompService.watch('/user/queue/log').subscribe(msg => { diff --git a/frontend/src/app/features/book/data/book-background-submission-keys.ts b/frontend/src/app/features/book/data/book-background-submission-keys.ts new file mode 100644 index 000000000..1c182a246 --- /dev/null +++ b/frontend/src/app/features/book/data/book-background-submission-keys.ts @@ -0,0 +1,5 @@ +import {bookCommandKeys} from './book-command-keys'; + +export const bookBackgroundSubmissionKeys = { + changeCovers: () => [...bookCommandKeys.all(), 'background-submission', 'change-covers'] as const, +}; diff --git a/frontend/src/app/features/book/data/book-background-submission.models.ts b/frontend/src/app/features/book/data/book-background-submission.models.ts new file mode 100644 index 000000000..945d93142 --- /dev/null +++ b/frontend/src/app/features/book/data/book-background-submission.models.ts @@ -0,0 +1,4 @@ +export interface ChangeCoversVariables { + readonly kind: 'regenerate' | 'generate'; + readonly bookIds: readonly number[]; +} diff --git a/frontend/src/app/features/book/data/book-background-submission.service.ts b/frontend/src/app/features/book/data/book-background-submission.service.ts new file mode 100644 index 000000000..9392e4eae --- /dev/null +++ b/frontend/src/app/features/book/data/book-background-submission.service.ts @@ -0,0 +1,36 @@ +import {HttpClient} from '@angular/common/http'; +import {inject, Injectable} from '@angular/core'; +import {mutationOptions} from '@tanstack/angular-query-experimental'; +import {lastValueFrom} from 'rxjs'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import {bookBackgroundSubmissionKeys} from './book-background-submission-keys'; +import {ChangeCoversVariables} from './book-background-submission.models'; + +@Injectable({providedIn: 'root'}) +export class BookBackgroundSubmissionService { + private readonly http = inject(HttpClient); + private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/books`; + + changeCovers() { + return mutationOptions({ + mutationKey: bookBackgroundSubmissionKeys.changeCovers(), + mutationFn: (variables: ChangeCoversVariables) => this.requestCoverChanges(variables), + }); + } + + private requestCoverChanges( + variables: ChangeCoversVariables, + ): Promise { + switch (variables.kind) { + case 'regenerate': + return this.postBookIds('/bulk-regenerate-covers', variables.bookIds); + case 'generate': + return this.postBookIds('/bulk-generate-custom-covers', variables.bookIds); + } + } + + private postBookIds(path: string, bookIds: readonly number[]): Promise { + return lastValueFrom(this.http.post(`${this.baseUrl}${path}`, {bookIds})); + } +} diff --git a/frontend/src/app/features/metadata/data/metadata-refresh-submission-keys.ts b/frontend/src/app/features/metadata/data/metadata-refresh-submission-keys.ts new file mode 100644 index 000000000..598006585 --- /dev/null +++ b/frontend/src/app/features/metadata/data/metadata-refresh-submission-keys.ts @@ -0,0 +1,3 @@ +export const metadataRefreshSubmissionKeys = { + refresh: () => ['metadata', 'background-submission', 'refresh'] as const, +}; diff --git a/frontend/src/app/features/metadata/data/metadata-refresh-submission.models.ts b/frontend/src/app/features/metadata/data/metadata-refresh-submission.models.ts new file mode 100644 index 000000000..05b7fd809 --- /dev/null +++ b/frontend/src/app/features/metadata/data/metadata-refresh-submission.models.ts @@ -0,0 +1,3 @@ +export interface RefreshMetadataVariables { + readonly bookIds: readonly number[]; +} diff --git a/frontend/src/app/features/metadata/data/metadata-refresh-submission.service.spec.ts b/frontend/src/app/features/metadata/data/metadata-refresh-submission.service.spec.ts new file mode 100644 index 000000000..2a233b8fc --- /dev/null +++ b/frontend/src/app/features/metadata/data/metadata-refresh-submission.service.spec.ts @@ -0,0 +1,77 @@ +import {TestBed} from '@angular/core/testing'; +import {QueryClient} from '@tanstack/angular-query-experimental'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import { + createQueryClientHarness, + flushSignalAndQueryEffects, +} from '../../../core/testing/query-testing'; +import { + MetadataBatchProgressNotification, + MetadataBatchStatus, +} from '../../../shared/model/metadata-batch-progress.model'; +import {AUTHORS_QUERY_KEY} from '../../author-browser/service/author-query-keys'; +import {bookQueryKeys} from '../../book/data/book-query-keys'; +import {MetadataRefreshSubmissionService} from './metadata-refresh-submission.service'; + +function batchProgress(status: MetadataBatchStatus): MetadataBatchProgressNotification { + return { + taskId: 'metadata-task-1', + completed: 1, + total: 1, + message: 'Refreshing metadata', + status, + review: false, + }; +} + +describe('MetadataRefreshSubmissionService batch reconciliation', () => { + let service: MetadataRefreshSubmissionService; + let queryClient: QueryClient; + + beforeEach(() => { + const harness = createQueryClientHarness(); + queryClient = harness.queryClient; + TestBed.configureTestingModule({ + providers: [...harness.providers, MetadataRefreshSubmissionService], + }); + service = TestBed.inject(MetadataRefreshSubmissionService); + flushSignalAndQueryEffects(); + }); + + afterEach(() => { + vi.useRealTimers(); + queryClient.clear(); + }); + + it('reconciles book and author queries when a batch completes', () => { + const invalidate = vi.spyOn(queryClient, 'invalidateQueries'); + service.handleBatchProgress(batchProgress(MetadataBatchStatus.COMPLETED)); + + expect(invalidate).toHaveBeenCalledWith({queryKey: bookQueryKeys.all()}); + expect(invalidate).toHaveBeenCalledWith({queryKey: AUTHORS_QUERY_KEY, exact: true}); + }); + + it('treats an error followed by silence as the end of the batch', () => { + vi.useFakeTimers(); + const invalidate = vi.spyOn(queryClient, 'invalidateQueries'); + service.handleBatchProgress(batchProgress(MetadataBatchStatus.ERROR)); + expect(invalidate).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(5000); + expect(invalidate).toHaveBeenCalledWith({queryKey: bookQueryKeys.all()}); + }); + + it('folds per-book errors into one end-of-batch reconciliation', () => { + vi.useFakeTimers(); + const invalidate = vi.spyOn(queryClient, 'invalidateQueries'); + service.handleBatchProgress(batchProgress(MetadataBatchStatus.ERROR)); + service.handleBatchProgress(batchProgress(MetadataBatchStatus.IN_PROGRESS)); + vi.advanceTimersByTime(10_000); + expect(invalidate).not.toHaveBeenCalled(); + + service.handleBatchProgress(batchProgress(MetadataBatchStatus.COMPLETED)); + expect(invalidate).toHaveBeenCalledTimes(2); + }); + +}); diff --git a/frontend/src/app/features/metadata/data/metadata-refresh-submission.service.ts b/frontend/src/app/features/metadata/data/metadata-refresh-submission.service.ts new file mode 100644 index 000000000..f06b8fdec --- /dev/null +++ b/frontend/src/app/features/metadata/data/metadata-refresh-submission.service.ts @@ -0,0 +1,67 @@ +import {HttpClient} from '@angular/common/http'; +import {inject, Injectable} from '@angular/core'; +import {mutationOptions, QueryClient} from '@tanstack/angular-query-experimental'; +import {lastValueFrom} from 'rxjs'; + +import {API_CONFIG} from '../../../core/config/api-config'; +import { + MetadataBatchProgressNotification, + MetadataBatchStatus, +} from '../../../shared/model/metadata-batch-progress.model'; +import {invalidateAuthorsQuery} from '../../author-browser/service/author-query-cache'; +import {invalidateAllBookQueries} from '../../book/data/book-query-cache'; +import {metadataRefreshSubmissionKeys} from './metadata-refresh-submission-keys'; +import {RefreshMetadataVariables} from './metadata-refresh-submission.models'; + +const ERROR_QUIET_PERIOD_MS = 5000; + +@Injectable({providedIn: 'root'}) +export class MetadataRefreshSubmissionService { + private readonly http = inject(HttpClient); + private readonly queryClient = inject(QueryClient); + private readonly taskUrl = `${API_CONFIG.BASE_URL}/api/v1/tasks/start`; + private errorReconcileTimer: ReturnType | null = null; + + refreshMetadata() { + return mutationOptions({ + mutationKey: metadataRefreshSubmissionKeys.refresh(), + mutationFn: ({bookIds}: RefreshMetadataVariables) => this.refresh(bookIds), + }); + } + + private refresh(bookIds: readonly number[]): Promise { + return lastValueFrom(this.http.post(this.taskUrl, { + taskType: 'REFRESH_METADATA_MANUAL', + options: {refreshType: 'BOOKS', bookIds}, + })); + } + + handleBatchProgress(progress: MetadataBatchProgressNotification): void { + this.clearErrorReconcileTimer(); + if (progress.status === MetadataBatchStatus.IN_PROGRESS) { + return; + } + if (progress.status === MetadataBatchStatus.ERROR) { + this.errorReconcileTimer = setTimeout(() => { + this.errorReconcileTimer = null; + reconcileMetadataRefresh(this.queryClient); + }, ERROR_QUIET_PERIOD_MS); + return; + } + reconcileMetadataRefresh(this.queryClient); + } + + private clearErrorReconcileTimer(): void { + if (this.errorReconcileTimer !== null) { + clearTimeout(this.errorReconcileTimer); + this.errorReconcileTimer = null; + } + } +} + +function reconcileMetadataRefresh(client: QueryClient): void { + // invalidateQueries never rejects (refetch errors surface through query + // state, not this promise), so there is nothing to await or catch. + void invalidateAllBookQueries(client); + invalidateAuthorsQuery(client); +}