refactor(books): add background job book submissions (#2189)

This commit is contained in:
Alex
2026-09-21 13:01:52 +01:00
committed by GitHub
parent 9be47b7ec0
commit ca6046c155
9 changed files with 209 additions and 3 deletions
+7
View File
@@ -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<typeof vi.fn> };
let taskService: { handleTaskProgress: ReturnType<typeof vi.fn> };
let metadataRefreshSubmissionService: { handleBatchProgress: ReturnType<typeof vi.fn> };
let libraryHealthService: { initWebsocket: ReturnType<typeof vi.fn>, fetchHealth: ReturnType<typeof vi.fn> };
let authService: { forceLogout: ReturnType<typeof vi.fn>, isAuthenticated: ReturnType<typeof signal> };
let libraryImportProgressService: { recordBookAdded: ReturnType<typeof vi.fn> };
@@ -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",
+7 -3
View File
@@ -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 => {
@@ -0,0 +1,5 @@
import {bookCommandKeys} from './book-command-keys';
export const bookBackgroundSubmissionKeys = {
changeCovers: () => [...bookCommandKeys.all(), 'background-submission', 'change-covers'] as const,
};
@@ -0,0 +1,4 @@
export interface ChangeCoversVariables {
readonly kind: 'regenerate' | 'generate';
readonly bookIds: readonly number[];
}
@@ -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<void> {
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<void> {
return lastValueFrom(this.http.post<void>(`${this.baseUrl}${path}`, {bookIds}));
}
}
@@ -0,0 +1,3 @@
export const metadataRefreshSubmissionKeys = {
refresh: () => ['metadata', 'background-submission', 'refresh'] as const,
};
@@ -0,0 +1,3 @@
export interface RefreshMetadataVariables {
readonly bookIds: readonly number[];
}
@@ -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);
});
});
@@ -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<typeof setTimeout> | null = null;
refreshMetadata() {
return mutationOptions({
mutationKey: metadataRefreshSubmissionKeys.refresh(),
mutationFn: ({bookIds}: RefreshMetadataVariables) => this.refresh(bookIds),
});
}
private refresh(bookIds: readonly number[]): Promise<void> {
return lastValueFrom(this.http.post<void>(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);
}