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
@@ -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);
}