feat(recoverable-job): add admin page

This commit is contained in:
Edouard Vanbelle
2026-07-29 07:57:34 +02:00
parent e1556e3d36
commit 4336eca4d1
8 changed files with 1232 additions and 8 deletions
+134
View File
@@ -0,0 +1,134 @@
/**
* Admin JobRegistry endpoints — `/api/admin/jobs*` (see
* `docs/plan/job-registry.md`). Powers the "Jobs" tab of the admin panel.
*
* Every mutation goes through the standard admin auth path (Bearer JWT
* + admin-middleware role check). Read endpoints are cheap enough to
* poll while the panel is open.
*/
import { apiFetch, apiJson } from '$lib/api/client';
import { getCsrfHeaders } from '$lib/api/csrf';
import type { Finding, JobOutcome, JobSummary, RunSummary } from '$lib/api/types';
const JSON_HEADERS = { 'Content-Type': 'application/json' };
/**
* Envelope wrapping the outcome from `POST /api/admin/jobs/{name}/trigger`.
* `ok: true` means "dispatch reached the handler"; the handler's own
* pass/fail is in `outcome.outcome`. For `consistency_batch`, per-child
* outcomes are inside `outcome.extra.per_check`.
*/
export interface TriggerResponse {
ok: boolean;
outcome: JobOutcome;
}
/** Envelope from `POST /api/admin/jobs/{name}/cancel`. `run_id` is
* the id of the run whose `Running` status was flipped to
* `CancelRequested` (null when nothing was in flight to cancel). */
export interface CancelResponse {
ok: boolean;
run_id: string | null;
}
/**
* `GET /api/admin/jobs` — full registry snapshot. One row per registered
* job (periodic + recoverable + coordinators like `consistency_batch`,
* which register as plain JobHandlers).
*/
export function listJobs(): Promise<JobSummary[]> {
return apiJson<JobSummary[]>('/api/admin/jobs', { credentials: 'same-origin' });
}
/**
* `POST /api/admin/jobs/{name}/trigger?force=X&deep=X` — dispatch a job
* on-demand. `force` bypasses per-tenant idempotency checks (e.g.
* `trash_cleanup` skipping when nothing is due). `deep` opts into slow
* variants (currently only `storage_consistency`, propagated by
* `consistency_batch` to every child).
*
* Throws on 4xx / 5xx with the backend's error message when present.
* A 404 means the job name isn't registered — surface that specifically
* so callers can distinguish "typo" from "handler blew up".
*/
export async function triggerJob(
name: string,
opts: { force?: boolean; deep?: boolean } = {}
): Promise<TriggerResponse> {
const params = new URLSearchParams();
if (opts.force) params.set('force', 'true');
if (opts.deep) params.set('deep', 'true');
const q = params.toString();
const url = `/api/admin/jobs/${encodeURIComponent(name)}/trigger${q ? `?${q}` : ''}`;
const res = await apiFetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: { ...JSON_HEADERS, ...getCsrfHeaders() }
});
if (!res.ok) {
let msg = `trigger failed: ${res.status}`;
try {
const body = (await res.json()) as { error?: string; message?: string };
msg = body.error ?? body.message ?? msg;
} catch {
/* no JSON body */
}
throw new Error(msg);
}
return (await res.json()) as TriggerResponse;
}
/**
* `POST /api/admin/jobs/{name}/cancel` — cooperatively request cancel
* of the currently running instance. The handler observes it on its
* next `store.status()` poll and returns `RunOutcome::Paused` at the
* next safe boundary. If nothing is running, this is a no-op that
* returns `run_id: null`.
*/
export async function cancelJob(name: string): Promise<CancelResponse> {
const res = await apiFetch(`/api/admin/jobs/${encodeURIComponent(name)}/cancel`, {
method: 'POST',
credentials: 'same-origin',
headers: { ...JSON_HEADERS, ...getCsrfHeaders() }
});
if (!res.ok) {
let msg = `cancel failed: ${res.status}`;
try {
const body = (await res.json()) as { error?: string; message?: string };
msg = body.error ?? body.message ?? msg;
} catch {
/* no JSON body */
}
throw new Error(msg);
}
return (await res.json()) as CancelResponse;
}
/**
* `GET /api/admin/jobs/{name}/runs?limit=N` — history of recoverable
* runs for `name`, newest first. Backend caps `limit` at 100.
*/
export function listRuns(name: string, limit = 20): Promise<RunSummary[]> {
return apiJson<RunSummary[]>(`/api/admin/jobs/${encodeURIComponent(name)}/runs?limit=${limit}`, {
credentials: 'same-origin'
});
}
/**
* `GET /api/admin/jobs/{name}/runs/{id}/findings?limit=N&offset=M` —
* paginated findings for a specific run. Empty list = clean run,
* 404 = unknown run id.
*/
export function listFindings(
name: string,
runId: string,
opts: { limit?: number; offset?: number } = {}
): Promise<Finding[]> {
const params = new URLSearchParams();
params.set('limit', String(opts.limit ?? 100));
if (opts.offset) params.set('offset', String(opts.offset));
return apiJson<Finding[]>(
`/api/admin/jobs/${encodeURIComponent(name)}/runs/${encodeURIComponent(runId)}/findings?${params}`,
{ credentials: 'same-origin' }
);
}