feat(recoverable-job): add admin page
This commit is contained in:
@@ -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' }
|
||||
);
|
||||
}
|
||||
@@ -522,3 +522,77 @@ export interface FolderAncestorsResponse {
|
||||
ancestors: FolderAncestor[];
|
||||
access_source: AccessSource;
|
||||
}
|
||||
|
||||
// ─── Job registry (Part 1 + Part 2) ────────────────────────────────────────
|
||||
//
|
||||
// Maps `src/infrastructure/scheduler/*` DTOs 1:1. See
|
||||
// `docs/plan/job-registry.md` for the backend contract; the shapes below
|
||||
// are what the `/api/admin/jobs*` endpoints emit.
|
||||
|
||||
/**
|
||||
* `JobOutcome` — the uniform outcome the scheduler logs and stores for
|
||||
* every job dispatch. Serialised with `#[serde(tag = "outcome")]` so the
|
||||
* discriminant is the `outcome` field, not the object key.
|
||||
*/
|
||||
export type JobOutcome =
|
||||
| { outcome: 'ok'; count: number; extra?: unknown }
|
||||
| { outcome: 'err'; message: string };
|
||||
|
||||
/**
|
||||
* `JobSummary` — one row per registered job in `GET /api/admin/jobs`.
|
||||
* Cadence + last-run bookkeeping. `interval_ms` / `next_run_at` are
|
||||
* `undefined` on on-demand jobs (serde skips `Option::None`).
|
||||
*/
|
||||
export interface JobSummary {
|
||||
name: string;
|
||||
interval_ms?: number;
|
||||
next_run_at?: string;
|
||||
last_run_at?: string;
|
||||
last_outcome?: JobOutcome;
|
||||
running: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* `RunStatus` values allowed in `jobs.recoverable_runs.status`. The
|
||||
* non-terminal set (Running / Paused / CancelRequested) is what the
|
||||
* DB's `one_active_run_per_job` partial unique index scopes.
|
||||
*/
|
||||
export type RunStatus = 'Running' | 'Paused' | 'CancelRequested' | 'Completed' | 'Failed';
|
||||
|
||||
/**
|
||||
* `RunSummary` — one row per recoverable-job run from
|
||||
* `GET /api/admin/jobs/{name}/runs`. Terminal + non-terminal rows both
|
||||
* appear. `stats` / `params` are opaque JSON — job-specific shape;
|
||||
* consumers should key off `job_name` to decide what to render.
|
||||
* `cursor_hex` is present only when the run has advanced past the
|
||||
* initial state (paused mid-scan is the typical case).
|
||||
*/
|
||||
export interface RunSummary {
|
||||
id: string;
|
||||
job_name: string;
|
||||
status: RunStatus;
|
||||
started_at: string;
|
||||
last_progress_at: string;
|
||||
completed_at?: string;
|
||||
stats: Record<string, unknown>;
|
||||
params: Record<string, unknown>;
|
||||
cursor_hex?: string;
|
||||
error_message?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* `Finding` — one row from `GET /api/admin/jobs/{name}/runs/{id}/findings`.
|
||||
* Persisted by consistency tenants via `store.record_finding()`. Consumers
|
||||
* key off `kind` to know the shape of `detail` (per-tenant JSON — e.g.
|
||||
* `stale_used_bytes` carries `{cached, actual, delta}`; `missing_blob`
|
||||
* carries `{blob_hash}`; …).
|
||||
*/
|
||||
export interface Finding {
|
||||
id: string;
|
||||
run_id: string;
|
||||
kind: string;
|
||||
severity: string;
|
||||
resource_id?: string;
|
||||
detail: Record<string, unknown>;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user