From c8bad5538bbc5a30293fdd7859b7c510a2acecc0 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 15:31:53 +0100 Subject: [PATCH] feat(web): hooks for the bulk jobs (covers, artist pictures, descriptions) One set of hooks for the three jobs: read the status (again and again while it runs, by itself stopping), start (optionally reading everything again) and stop. --- web/src/api/jobs.test.tsx | 93 +++++++++++++++++++++++++++++++++++++++ web/src/api/jobs.ts | 42 ++++++++++++++++++ 2 files changed, 135 insertions(+) create mode 100644 web/src/api/jobs.test.tsx create mode 100644 web/src/api/jobs.ts diff --git a/web/src/api/jobs.test.tsx b/web/src/api/jobs.test.tsx new file mode 100644 index 0000000..c4cc24e --- /dev/null +++ b/web/src/api/jobs.test.tsx @@ -0,0 +1,93 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, renderHook, waitFor } from '@testing-library/react' +import type { ReactNode } from 'react' +import { expect, test } from 'vitest' +import { apiError, mockFetch } from '@/test/mockFetch' +import { useJobStatus, useStartJob, useStopJob } from './jobs' + +function setup() { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + const wrapper = ({ children }: { children: ReactNode }) => {children} + return { client, wrapper } +} + +const started = () => new Response(JSON.stringify({ status: 'started' }), { status: 202, headers: { 'Content-Type': 'application/json' } }) +const none = () => new Response(null, { status: 204 }) + +test.each([ + ['covers', '/api/v1/library/covers'], + ['artist-images', '/api/v1/library/artist-images'], + ['descriptions', '/api/v1/library/descriptions'], +] as const)('the %s job is read from its own address', async (kind, path) => { + const { calls } = mockFetch({ [`GET ${path}`]: () => ({ running: false }) }) + const { result } = renderHook(() => useJobStatus(kind), { wrapper: setup().wrapper }) + await waitFor(() => expect(result.current.data).toEqual({ running: false })) + expect(calls.map((c) => c.key)).toEqual([`GET ${path}`]) +}) + +test('while a job runs its status is read again and again, and it stops by itself when the job ends', async () => { + let n = 0 + const { calls } = mockFetch({ + 'GET /api/v1/library/covers': () => (++n < 3 ? { running: true, progress: { done: n, total: 10 } } : { running: false }), + }) + const { result } = renderHook(() => useJobStatus('covers', { intervalMs: 20 }), { wrapper: setup().wrapper }) + await waitFor(() => expect(result.current.data?.running).toBe(false), { timeout: 2000 }) + const seen = calls.length + await new Promise((r) => setTimeout(r, 120)) + expect(calls).toHaveLength(seen) + expect(seen).toBe(3) +}) + +test.each([ + ['covers', '/api/v1/library/covers'], + ['artist-images', '/api/v1/library/artist-images'], + ['descriptions', '/api/v1/library/descriptions'], +] as const)('starting the %s job is a POST that reads everything again only when asked', async (kind, path) => { + const { calls } = mockFetch({ [`POST ${path}`]: started, [`GET ${path}`]: () => ({ running: true }) }) + const { result } = renderHook(() => useStartJob(kind), { wrapper: setup().wrapper }) + await act(() => result.current.mutateAsync({ refresh: false })) + await act(() => result.current.mutateAsync({ refresh: true })) + const posts = calls.filter((c) => c.key === `POST ${path}`) + expect(posts[0].url.searchParams.has('refresh')).toBe(false) + expect(posts[1].url.searchParams.get('refresh')).toBe('true') +}) + +test('starting a job makes its status be read at once, so the page follows it', async () => { + let running = false + const { calls } = mockFetch({ + 'GET /api/v1/library/covers': () => ({ running }), + 'POST /api/v1/library/covers': () => { + running = true + return started() + }, + }) + const { wrapper } = setup() + const { result } = renderHook(() => ({ status: useJobStatus('covers', { intervalMs: 20 }), start: useStartJob('covers') }), { wrapper }) + await waitFor(() => expect(result.current.status.data?.running).toBe(false)) + await act(() => result.current.start.mutateAsync({ refresh: false })) + await waitFor(() => expect(result.current.status.data?.running).toBe(true)) + expect(calls.filter((c) => c.key === 'GET /api/v1/library/covers').length).toBeGreaterThanOrEqual(2) +}) + +test('a job already running is refused, and the status is still read so the page follows the one that runs', async () => { + const { calls } = mockFetch({ + 'POST /api/v1/library/descriptions': () => apiError(409, 'descriptions_job_running'), + 'GET /api/v1/library/descriptions': () => ({ running: true }), + }) + const { result } = renderHook(() => ({ status: useJobStatus('descriptions', { intervalMs: 5000 }), start: useStartJob('descriptions') }), { + wrapper: setup().wrapper, + }) + await waitFor(() => expect(result.current.status.isSuccess).toBe(true)) + await act(() => result.current.start.mutateAsync({ refresh: false }).catch(() => undefined)) + await waitFor(() => expect(calls.filter((c) => c.key === 'GET /api/v1/library/descriptions')).toHaveLength(2)) +}) + +test('stopping is a DELETE and the status is read again', async () => { + const { calls } = mockFetch({ 'DELETE /api/v1/library/artist-images': none, 'GET /api/v1/library/artist-images': () => ({ running: false }) }) + const { result } = renderHook(() => ({ status: useJobStatus('artist-images'), stop: useStopJob('artist-images') }), { wrapper: setup().wrapper }) + await waitFor(() => expect(result.current.status.isSuccess).toBe(true)) + await act(() => result.current.stop.mutateAsync()) + await waitFor(() => + expect(calls.map((c) => c.key)).toEqual(['GET /api/v1/library/artist-images', 'DELETE /api/v1/library/artist-images', 'GET /api/v1/library/artist-images']), + ) +}) diff --git a/web/src/api/jobs.ts b/web/src/api/jobs.ts new file mode 100644 index 0000000..e9fac9f --- /dev/null +++ b/web/src/api/jobs.ts @@ -0,0 +1,42 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { api } from './client' +import type { components } from './schema' + +export type CoversJobStatus = components['schemas']['CoversJobStatus'] +export type ArtistJobStatus = components['schemas']['ArtistJobStatus'] + +/** The bulk jobs that go through the whole library, each at its own address under `/library`. */ +export type JobKind = 'covers' | 'artist-images' | 'descriptions' +export type JobStatus = K extends 'covers' ? CoversJobStatus : ArtistJobStatus + +const statusKey = (kind: JobKind) => ['library', kind] + +/** Whether the job runs, how far it is, and how the last one ended. While it runs it is read again every `intervalMs`. */ +export function useJobStatus(kind: K, { intervalMs = 2000 }: { intervalMs?: number } = {}) { + return useQuery({ + queryKey: statusKey(kind), + queryFn: () => api.get>(`/library/${kind}`), + refetchInterval: (query) => (query.state.data?.running ? intervalMs : false), + }) +} + +/** + * Starts the job in the background. `refresh` goes through every item again, also those with a good answer. + * Whatever the answer (also "already running"), the status is read at once so the page follows the job. + */ +export function useStartJob(kind: JobKind) { + const client = useQueryClient() + return useMutation({ + mutationFn: ({ refresh }: { refresh: boolean }) => api.post<{ status: 'started' }>(refresh ? `/library/${kind}?refresh=true` : `/library/${kind}`), + onSettled: () => client.invalidateQueries({ queryKey: statusKey(kind) }), + }) +} + +/** Asks the job to end after the item it is on. What it already did stays. */ +export function useStopJob(kind: JobKind) { + const client = useQueryClient() + return useMutation({ + mutationFn: () => api.del(`/library/${kind}`), + onSettled: () => client.invalidateQueries({ queryKey: statusKey(kind) }), + }) +}