refactor(lab): move execution to Worker and manage replay and transfer lifecycles
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import { resolveObservationSessionReplay } from "../observation/useObservationSessions";
|
||||
import type { ObservationSessionReplayLaunch } from "../observation/sessionArchive";
|
||||
import type { CanonicalLabReplayDescriptor } from "./canonicalLabReplay";
|
||||
|
||||
export interface LabReplayProgress {
|
||||
phase: "checking" | "preparing" | "opening";
|
||||
fraction: number | null;
|
||||
}
|
||||
export type LabReplayResolver = (id: string, base: ObservationSessionReplayLaunch,
|
||||
options: { signal: AbortSignal }) => Promise<CanonicalLabReplayDescriptor>;
|
||||
|
||||
/** Shared preparation for the eye, download and offline pin. Never runs inference. */
|
||||
export async function prepareLabReplay(id: string, sourceId: string, resolve: LabReplayResolver,
|
||||
{ signal, onProgress, fetcher }: {
|
||||
signal: AbortSignal;
|
||||
onProgress?: (progress: LabReplayProgress) => void;
|
||||
fetcher?: typeof fetch;
|
||||
}) {
|
||||
const request = new AbortController();
|
||||
const abort = () => request.abort();
|
||||
signal.addEventListener("abort", abort, { once: true });
|
||||
const timer = globalThis.setTimeout(abort, 30 * 60 * 1000);
|
||||
const publish = (progress: LabReplayProgress) => {
|
||||
request.signal.throwIfAborted();
|
||||
onProgress?.(progress);
|
||||
};
|
||||
try {
|
||||
signal.throwIfAborted();
|
||||
publish({ phase: "checking", fraction: null });
|
||||
const base = await resolveObservationSessionReplay(sourceId, {
|
||||
signal: request.signal, fetcher, maximumWaitMs: 30 * 60 * 1000,
|
||||
onUpdate: (state) => publish({ phase: "preparing", fraction: state.progress }),
|
||||
});
|
||||
publish({ phase: "preparing", fraction: null });
|
||||
const replay = await resolve(id, base, { signal: request.signal });
|
||||
request.signal.throwIfAborted();
|
||||
return { base, replay };
|
||||
} catch (error) {
|
||||
if (request.signal.aborted && !signal.aborted) {
|
||||
throw new Error("Подготовка записи заняла слишком много времени. Повторите загрузку.");
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
globalThis.clearTimeout(timer);
|
||||
signal.removeEventListener("abort", abort);
|
||||
}
|
||||
}
|
||||
|
||||
export function labReplayProgressView(progress: LabReplayProgress) {
|
||||
const labels = { checking: "Проверка доступности записи", preparing: "Подготовка записи",
|
||||
opening: "Открытие записи" };
|
||||
const value = progress.fraction === null || !Number.isFinite(progress.fraction)
|
||||
? undefined : Math.min(1, Math.max(0, progress.fraction));
|
||||
return { label: labels[progress.phase], value,
|
||||
text: value === undefined ? labels[progress.phase]
|
||||
: `${labels[progress.phase]} · ${Math.round(value * 100)}%` };
|
||||
}
|
||||
@@ -170,9 +170,8 @@ function evidenceFromSession(
|
||||
`LAB-каталог вернул сессию ${session.id} без типизированной связи с источником.`,
|
||||
);
|
||||
}
|
||||
// Historical LABs retain their archive and replay adapters. Observatory is
|
||||
// the portable-profile product; a familiar LAB label is not admission.
|
||||
if (session.lab.replayCapability?.kind !== "portable-result-review") return null;
|
||||
// History follows source identity. Playback admission remains independently
|
||||
// validated below; an unavailable viewer must never erase a completed run.
|
||||
const recordedRun = observatoryRecordedRunBinding(session.id, session.lab);
|
||||
return {
|
||||
sessionId: session.id,
|
||||
@@ -303,12 +302,10 @@ async function readCatalogPages(
|
||||
throw new ObservatoryCatalogContractError("Каталог повторил сессию между страницами.");
|
||||
}
|
||||
seenIds.add(item.id);
|
||||
// Do not accumulate legacy provenance while walking the shared catalog.
|
||||
if (scope === "source" || item.lab?.replayCapability?.kind === "portable-result-review") {
|
||||
items.push(item);
|
||||
} else if (!item.lab) {
|
||||
if (scope === "laboratory" && !item.lab) {
|
||||
throw new ObservatoryCatalogContractError("LAB-каталог вернул исходную сессию.");
|
||||
}
|
||||
items.push(item);
|
||||
}
|
||||
cursor = page.nextCursor;
|
||||
if (cursor === null) return { items, hasMore: false };
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ObservatoryEvidence } from "./catalog";
|
||||
import type { ObservatoryRecordedRunBinding } from "./recordedRun";
|
||||
|
||||
const SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
||||
@@ -26,7 +27,7 @@ export class ObservatoryCatalogMutationError extends Error {
|
||||
}
|
||||
|
||||
export async function renameObservatoryLabProjection(
|
||||
binding: ObservatoryRecordedRunBinding,
|
||||
binding: ObservatoryRecordedRunBinding | Pick<ObservatoryEvidence, "sessionId" | "lab">,
|
||||
displayName: string,
|
||||
{
|
||||
signal,
|
||||
@@ -78,7 +79,7 @@ export async function renameObservatoryLabProjection(
|
||||
}
|
||||
|
||||
export async function deleteObservatoryLabProjection(
|
||||
binding: ObservatoryRecordedRunBinding,
|
||||
binding: ObservatoryRecordedRunBinding | Pick<ObservatoryEvidence, "sessionId" | "lab">,
|
||||
{
|
||||
signal,
|
||||
fetcher = globalThis.fetch,
|
||||
@@ -113,7 +114,16 @@ export async function deleteObservatoryLabProjection(
|
||||
}
|
||||
}
|
||||
|
||||
function admittedProjectionId(binding: ObservatoryRecordedRunBinding): string {
|
||||
function admittedProjectionId(binding: ObservatoryRecordedRunBinding | Pick<ObservatoryEvidence, "sessionId" | "lab">): string {
|
||||
// Catalog ownership is independent of whether this client supports replay.
|
||||
// The server verifies the typed LAB projection against its source rows.
|
||||
if ("lab" in binding) {
|
||||
if (!SAFE_SESSION_ID.test(binding.sessionId) || !binding.lab.labId
|
||||
|| !binding.lab.resultId || binding.lab.sourceSessionId === binding.sessionId) {
|
||||
throw new ObservatoryCatalogMutationError("Выбранный результат не допущен к изменению каталога AI Inference.");
|
||||
}
|
||||
return binding.sessionId;
|
||||
}
|
||||
const sessionId = binding.evidenceSessionId;
|
||||
const admittedViewer = (
|
||||
binding.kind === "canonical-recorded-rerun"
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { ObservatoryRecordedJob, ObservatoryRecordedJobFetch } from "./recordedJobs";
|
||||
|
||||
export function failedRunDetail(job: Pick<ObservatoryRecordedJob, "terminalMessage">): string {
|
||||
const message = job.terminalMessage ?? "";
|
||||
if (/source-member|source transport|Content-Length|camera-source/i.test(message)) {
|
||||
return "Не удалось подготовить исходную запись";
|
||||
}
|
||||
if (/assemble|export|presentation/i.test(message)) return "Не удалось собрать запись результата";
|
||||
if (/Docker Engine|container.*start|start.*container/i.test(message)) return "Не удалось запустить вычислительный контейнер";
|
||||
if (/exit 143|exit=143|cancel|interrupted/i.test(message)) return "Расчёт прерван до получения результата";
|
||||
if (/prepare/i.test(message)) return "Ошибка подготовки расчёта";
|
||||
return "Расчёт завершился ошибкой; готового результата нет";
|
||||
}
|
||||
|
||||
export async function deleteFailedRunProjection(
|
||||
job: Pick<ObservatoryRecordedJob, "jobId" | "state" | "resultId">,
|
||||
fetcher: ObservatoryRecordedJobFetch = globalThis.fetch,
|
||||
): Promise<void> {
|
||||
if (!/^observatory-run-[a-f0-9]{32}$/.test(job.jobId) || job.state !== "failed" || job.resultId !== null) {
|
||||
throw new Error("Удалить можно только ошибочную попытку без результата.");
|
||||
}
|
||||
const response = await fetcher(`/api/v1/observatory/ai-runs/${encodeURIComponent(job.jobId)}`, { method: "DELETE" });
|
||||
if (response.status !== 204) throw new Error("Не удалось удалить попытку из истории. Обновите список и повторите.");
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
fetchObservatoryPortableLaboratorySetups,
|
||||
preflightObservatoryLaboratorySetup,
|
||||
selectableObservatorySetups,
|
||||
type ObservatoryLaboratoryRunPreflight,
|
||||
type ObservatoryLaboratorySetupCatalog,
|
||||
} from "./laboratorySetups";
|
||||
|
||||
type SetupCatalogState = "idle" | "loading" | "ready" | "refreshing" | "error";
|
||||
export type SetupPreflightState =
|
||||
| { readonly kind: "idle" }
|
||||
| { readonly kind: "checking" }
|
||||
| { readonly kind: "ready"; readonly value: ObservatoryLaboratoryRunPreflight }
|
||||
| { readonly kind: "error"; readonly message: string };
|
||||
|
||||
export function useObservatoryLaboratorySetups(sourceSessionId: string) {
|
||||
const [catalog, setCatalog] = useState<ObservatoryLaboratorySetupCatalog | null>(null);
|
||||
const [state, setState] = useState<SetupCatalogState>("idle");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [selectedSetupId, setSelectedSetupId] = useState("");
|
||||
const [revision, setRevision] = useState(0);
|
||||
const [preflight, setPreflight] = useState<SetupPreflightState>({ kind: "idle" });
|
||||
const requestSequence = useRef(0);
|
||||
const preflightRequest = useRef<AbortController | null>(null);
|
||||
const activeCatalog = catalog?.sourceSessionId === sourceSessionId ? catalog : null;
|
||||
const selectableSetups = useMemo(() => selectableObservatorySetups(activeCatalog), [activeCatalog]);
|
||||
const selectedSetup = selectableSetups.find((setup) => setup.setupId === selectedSetupId) ?? null;
|
||||
const selectedDefinitionSha256 = selectedSetup?.runDefinition?.definitionSha256 ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
preflightRequest.current?.abort();
|
||||
preflightRequest.current = null;
|
||||
if (!sourceSessionId) {
|
||||
setCatalog(null);
|
||||
setState("idle");
|
||||
setError(null);
|
||||
setSelectedSetupId("");
|
||||
setPreflight({ kind: "idle" });
|
||||
return;
|
||||
}
|
||||
const sequence = ++requestSequence.current;
|
||||
const request = new AbortController();
|
||||
setState((current) => activeCatalog && current !== "idle" ? "refreshing" : "loading");
|
||||
setError(null);
|
||||
setPreflight({ kind: "idle" });
|
||||
// Archived definitions belong to evidence, not to the calculation selector.
|
||||
void fetchObservatoryPortableLaboratorySetups(sourceSessionId, { signal: request.signal })
|
||||
.then((next) => {
|
||||
if (request.signal.aborted || requestSequence.current !== sequence) return;
|
||||
setCatalog(next);
|
||||
const selectable = selectableObservatorySetups(next);
|
||||
setSelectedSetupId((current) => (
|
||||
selectable.some((setup) => setup.setupId === current)
|
||||
? current
|
||||
: selectable[0]?.setupId ?? ""
|
||||
));
|
||||
setState("ready");
|
||||
})
|
||||
.catch((caught: unknown) => {
|
||||
if (request.signal.aborted || requestSequence.current !== sequence) return;
|
||||
setState("error");
|
||||
setError(caught instanceof Error && caught.message.trim()
|
||||
? caught.message
|
||||
: "Каталог профилей недоступен.");
|
||||
});
|
||||
return () => request.abort();
|
||||
}, [revision, sourceSessionId]);
|
||||
|
||||
useEffect(() => () => preflightRequest.current?.abort(), []);
|
||||
|
||||
useEffect(() => {
|
||||
preflightRequest.current?.abort();
|
||||
preflightRequest.current = null;
|
||||
setPreflight((current) => current.kind === "idle" ? current : { kind: "idle" });
|
||||
}, [selectedSetupId, sourceSessionId, selectedDefinitionSha256]);
|
||||
|
||||
const selectSetup = useCallback((setupId: string) => {
|
||||
preflightRequest.current?.abort();
|
||||
preflightRequest.current = null;
|
||||
setSelectedSetupId(setupId);
|
||||
setPreflight({ kind: "idle" });
|
||||
}, []);
|
||||
|
||||
const refresh = useCallback(() => setRevision((value) => value + 1), []);
|
||||
|
||||
const check = useCallback(async () => {
|
||||
if (!sourceSessionId || !selectedSetup || preflight.kind === "checking") return;
|
||||
preflightRequest.current?.abort();
|
||||
const request = new AbortController();
|
||||
preflightRequest.current = request;
|
||||
setPreflight({ kind: "checking" });
|
||||
try {
|
||||
const value = await preflightObservatoryLaboratorySetup(
|
||||
sourceSessionId,
|
||||
selectedSetup,
|
||||
{ signal: request.signal },
|
||||
);
|
||||
if (request.signal.aborted || preflightRequest.current !== request) return;
|
||||
setPreflight({ kind: "ready", value });
|
||||
} catch (caught) {
|
||||
if (request.signal.aborted || preflightRequest.current !== request) return;
|
||||
setPreflight({
|
||||
kind: "error",
|
||||
message: caught instanceof Error && caught.message.trim()
|
||||
? caught.message
|
||||
: "Не удалось проверить возможность запуска.",
|
||||
});
|
||||
} finally {
|
||||
if (preflightRequest.current === request) preflightRequest.current = null;
|
||||
}
|
||||
}, [preflight.kind, selectedSetup, sourceSessionId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (state !== "ready" || !selectedSetup || preflight.kind !== "idle") return;
|
||||
void check();
|
||||
}, [check, preflight.kind, selectedSetup, state]);
|
||||
|
||||
return {
|
||||
catalog: activeCatalog,
|
||||
selectableSetups,
|
||||
state,
|
||||
error,
|
||||
selectedSetupId: selectedSetup?.setupId ?? "",
|
||||
selectedSetup,
|
||||
selectSetup,
|
||||
refresh,
|
||||
preflight,
|
||||
check,
|
||||
};
|
||||
}
|
||||
@@ -1,207 +0,0 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { fetchRecordedProgress, type RecordedProgressView } from "./recordedProgress";
|
||||
|
||||
import {
|
||||
fetchObservatoryRecordedJobs,
|
||||
retryObservatoryRecordedJobPublication,
|
||||
submitObservatoryRecordedJob,
|
||||
type ObservatoryRecordedJob,
|
||||
} from "./recordedJobs";
|
||||
|
||||
type RecordedJobsState =
|
||||
| "idle"
|
||||
| "loading"
|
||||
| "ready"
|
||||
| "refreshing"
|
||||
| "submitting"
|
||||
| "retrying-publication"
|
||||
| "error";
|
||||
|
||||
interface JobSnapshot {
|
||||
readonly selectionKey: string;
|
||||
readonly jobs: readonly ObservatoryRecordedJob[];
|
||||
readonly state: RecordedJobsState;
|
||||
readonly error: string | null;
|
||||
readonly progress?: RecordedProgressView | null;
|
||||
}
|
||||
const EMPTY_JOBS = [] as const;
|
||||
const OPEN_STATES = new Set([
|
||||
"accepted", "queued", "claimed", "running", "paused", "preemption-pending",
|
||||
"reconciliation-required",
|
||||
]);
|
||||
const POLL_INTERVAL_MS = 1_500;
|
||||
|
||||
export function useObservatoryRecordedJobs(
|
||||
sourceSessionId: string,
|
||||
setupId: string,
|
||||
definitionSha256: string,
|
||||
) {
|
||||
const selectionKey = JSON.stringify([sourceSessionId, setupId, definitionSha256]);
|
||||
const [snapshot, setSnapshot] = useState<JobSnapshot>({
|
||||
selectionKey: "", jobs: EMPTY_JOBS, state: "idle", error: null,
|
||||
});
|
||||
const [revision, setRevision] = useState(0);
|
||||
const requestRef = useRef<AbortController | null>(null);
|
||||
const requestSequence = useRef(0);
|
||||
const idempotencyKeys = useRef(new Map<string, string>());
|
||||
const observedJobId = useRef<string | null>(null);
|
||||
const hasSelection = Boolean(sourceSessionId && setupId && definitionSha256);
|
||||
// A source/profile change must not display even one render of the previous queue.
|
||||
const current = snapshot.selectionKey === selectionKey ? snapshot : null;
|
||||
const jobs = current?.jobs ?? EMPTY_JOBS;
|
||||
const state = current?.state ?? (hasSelection ? "loading" : "idle");
|
||||
const error = current?.error ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
requestRef.current?.abort();
|
||||
requestRef.current = null;
|
||||
if (!hasSelection) {
|
||||
setSnapshot({ selectionKey, jobs: EMPTY_JOBS, state: "idle", error: null });
|
||||
return;
|
||||
}
|
||||
const sequence = ++requestSequence.current;
|
||||
const request = new AbortController();
|
||||
requestRef.current = request;
|
||||
setSnapshot({
|
||||
selectionKey, jobs,
|
||||
state: jobs.length > 0 ? "refreshing" : "loading", error: null,
|
||||
progress: current?.progress ?? null,
|
||||
});
|
||||
void fetchObservatoryRecordedJobs(sourceSessionId, setupId, {
|
||||
definitionSha256, signal: request.signal,
|
||||
}).then(async (next) => {
|
||||
if (request.signal.aborted || requestSequence.current !== sequence) return;
|
||||
const pending = next.find((job) => OPEN_STATES.has(job.state));
|
||||
const progress = pending
|
||||
? await fetchRecordedProgress(pending, { signal: request.signal }).catch(() => null)
|
||||
: null;
|
||||
if (request.signal.aborted || requestSequence.current !== sequence) return;
|
||||
if (pending) observedJobId.current = pending.jobId;
|
||||
setSnapshot({ selectionKey, jobs: next, state: "ready", error: null, progress });
|
||||
}).catch((caught: unknown) => {
|
||||
if (request.signal.aborted || requestSequence.current !== sequence) return;
|
||||
setSnapshot({
|
||||
selectionKey, jobs, state: "error",
|
||||
error: caught instanceof Error && caught.message.trim()
|
||||
? caught.message
|
||||
: "Очередь расчётов недоступна.",
|
||||
});
|
||||
}).finally(() => {
|
||||
if (requestRef.current === request) requestRef.current = null;
|
||||
});
|
||||
return () => request.abort();
|
||||
}, [revision, selectionKey]);
|
||||
|
||||
useEffect(() => () => requestRef.current?.abort(), []);
|
||||
|
||||
const latestJob = jobs[0] ?? null;
|
||||
const activeJob = jobs.find((job) => OPEN_STATES.has(job.state)) ?? null;
|
||||
const publicationPending = jobs.some((job) => job.publication.state === "pending");
|
||||
// Do not promote historical terminal logs to a new operator action's error.
|
||||
const computationFailed = latestJob?.state === "failed"
|
||||
&& latestJob.jobId === observedJobId.current;
|
||||
|
||||
useEffect(() => {
|
||||
if ((state !== "ready" && state !== "error") || (!activeJob && !publicationPending)) return;
|
||||
const timer = globalThis.setTimeout(
|
||||
() => setRevision((value) => value + 1),
|
||||
POLL_INTERVAL_MS,
|
||||
);
|
||||
return () => globalThis.clearTimeout(timer);
|
||||
}, [activeJob, publicationPending, revision, state]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!latestJob || activeJob) return;
|
||||
idempotencyKeys.current.delete(selectionKey);
|
||||
}, [activeJob, latestJob, selectionKey]);
|
||||
|
||||
const refresh = useCallback(() => setRevision((value) => value + 1), []);
|
||||
|
||||
const submit = useCallback(async (
|
||||
portableBinding: {
|
||||
readonly definitionSha256: string;
|
||||
readonly checkSha256: string;
|
||||
} | null = null,
|
||||
): Promise<ObservatoryRecordedJob | null> => {
|
||||
if (!hasSelection || state !== "ready"
|
||||
|| portableBinding?.definitionSha256 !== definitionSha256
|
||||
|| publicationPending || latestJob?.publication.state === "failed") return null;
|
||||
if (activeJob) return activeJob;
|
||||
requestRef.current?.abort();
|
||||
const request = new AbortController();
|
||||
requestRef.current = request;
|
||||
const key = idempotencyKeys.current.get(selectionKey) ?? createIdempotencyKey();
|
||||
idempotencyKeys.current.set(selectionKey, key);
|
||||
setSnapshot({ selectionKey, jobs, state: "submitting", error: null });
|
||||
try {
|
||||
const job = await submitObservatoryRecordedJob(
|
||||
sourceSessionId, setupId, key, portableBinding, { signal: request.signal },
|
||||
);
|
||||
if (request.signal.aborted || requestRef.current !== request) return null;
|
||||
observedJobId.current = job.jobId;
|
||||
setSnapshot({
|
||||
selectionKey, jobs: [job, ...jobs.filter((candidate) => candidate.jobId !== job.jobId)],
|
||||
state: "ready", error: null,
|
||||
});
|
||||
return job;
|
||||
} catch (caught) {
|
||||
if (request.signal.aborted || requestRef.current !== request) return null;
|
||||
setSnapshot({
|
||||
selectionKey, jobs, state: "error",
|
||||
error: caught instanceof Error && caught.message.trim()
|
||||
? caught.message
|
||||
: "Не удалось поставить расчёт в очередь.",
|
||||
});
|
||||
return null;
|
||||
} finally {
|
||||
if (requestRef.current === request) requestRef.current = null;
|
||||
}
|
||||
}, [activeJob, definitionSha256, hasSelection, jobs, latestJob,
|
||||
publicationPending, selectionKey, setupId, sourceSessionId, state]);
|
||||
|
||||
const retryPublication = useCallback(async (): Promise<ObservatoryRecordedJob | null> => {
|
||||
if (!latestJob || latestJob.publication.state !== "failed"
|
||||
|| state === "retrying-publication") return null;
|
||||
requestRef.current?.abort();
|
||||
const request = new AbortController();
|
||||
requestRef.current = request;
|
||||
setSnapshot({ selectionKey, jobs, state: "retrying-publication", error: null });
|
||||
try {
|
||||
const job = await retryObservatoryRecordedJobPublication(latestJob.jobId, {
|
||||
signal: request.signal,
|
||||
});
|
||||
if (request.signal.aborted || requestRef.current !== request) return null;
|
||||
setSnapshot({
|
||||
selectionKey, jobs: [job, ...jobs.filter((candidate) => candidate.jobId !== job.jobId)],
|
||||
state: "ready", error: null,
|
||||
});
|
||||
return job;
|
||||
} catch (caught) {
|
||||
if (request.signal.aborted || requestRef.current !== request) return null;
|
||||
setSnapshot({
|
||||
selectionKey, jobs, state: "error",
|
||||
error: caught instanceof Error && caught.message.trim()
|
||||
? caught.message
|
||||
: "Не удалось повторить публикацию результата.",
|
||||
});
|
||||
return null;
|
||||
} finally {
|
||||
if (requestRef.current === request) requestRef.current = null;
|
||||
}
|
||||
}, [jobs, latestJob, selectionKey, state]);
|
||||
|
||||
return {
|
||||
jobs, latestJob, activeJob, publicationPending, computationFailed,
|
||||
progress: current?.progress ?? null,
|
||||
state, error, refresh, submit, retryPublication,
|
||||
};
|
||||
}
|
||||
|
||||
function createIdempotencyKey(): string {
|
||||
const entropy = typeof globalThis.crypto?.randomUUID === "function"
|
||||
? globalThis.crypto.randomUUID()
|
||||
: `${Date.now().toString(36)}-${Math.random().toString(16).slice(2)}`;
|
||||
return `observatory-ui:${entropy}`;
|
||||
}
|
||||
|
||||
export type ObservatoryRecordedJobsController = ReturnType<typeof useObservatoryRecordedJobs>;
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { LocalLabCopy } from "./localLabStorage";
|
||||
|
||||
export function formatLocalLabSize(copy: LocalLabCopy | undefined, available: boolean) {
|
||||
if (!available) return "размер уточняется";
|
||||
if (!copy?.local) return "0 Б на устройстве";
|
||||
const units = ["Б", "КБ", "МБ", "ГБ"];
|
||||
let value = copy.bytes;
|
||||
let unit = 0;
|
||||
while (value >= 1000 && unit < units.length - 1) { value /= 1000; unit += 1; }
|
||||
return `${new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 1 }).format(value)} ${units[unit]}`;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { prepareLabReplay, type LabReplayProgress } from "../laboratory/prepareLabReplay";
|
||||
import { resolveAICompositionReplay, resolveCanonicalLabReplay } from "../laboratory/canonicalLabReplay";
|
||||
|
||||
export interface LocalLabCopy {
|
||||
local: boolean;
|
||||
pinned: boolean;
|
||||
bytes: number;
|
||||
last_used: number;
|
||||
}
|
||||
export interface LocalLabStorage {
|
||||
retention_days: number;
|
||||
entries: Readonly<Record<string, LocalLabCopy>>;
|
||||
}
|
||||
const endpoint = "/api/v1/storage/laboratory";
|
||||
|
||||
async function request(path = "", method = "GET", body?: unknown): Promise<LocalLabStorage> {
|
||||
const response = await fetch(`${endpoint}${path}`, {
|
||||
method, credentials: "same-origin", cache: "no-store",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
const value = await response.json();
|
||||
if (!response.ok) throw new Error(value.detail ?? "Хранилище недоступно.");
|
||||
if (!Number.isInteger(value.retention_days) || value.retention_days < 1
|
||||
|| value.retention_days > 365 || !value.entries || typeof value.entries !== "object"
|
||||
|| Array.isArray(value.entries)) throw new Error("Некорректные настройки хранения.");
|
||||
for (const copy of Object.values(value.entries) as LocalLabCopy[]) {
|
||||
if (typeof copy.local !== "boolean" || typeof copy.pinned !== "boolean"
|
||||
|| !Number.isSafeInteger(copy.bytes) || copy.bytes < 0
|
||||
|| !Number.isFinite(copy.last_used)) throw new Error("Некорректное состояние локальной копии.");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
export const saveLabRetention = (days: number) => request("/policy", "PUT", { retention_days: days });
|
||||
export const pinLabCopy = (id: string, pinned: boolean) => request(`/copies/${encodeURIComponent(id)}/pin`, "PUT", { pinned });
|
||||
export const removeLabCopy = (id: string) => request(`/copies/${encodeURIComponent(id)}`, "DELETE");
|
||||
|
||||
export async function prepareLocalLabCopy(id: string, sourceId: string, composition: boolean,
|
||||
options: { signal: AbortSignal; onProgress?: (value: LabReplayProgress) => void }) {
|
||||
return prepareLabReplay(id, sourceId, (resultId, base, request) => composition
|
||||
? resolveAICompositionReplay(resultId, base, request)
|
||||
: resolveCanonicalLabReplay(resultId, base, { ...request,
|
||||
sourceKind: id.startsWith("m49-tgs") ? "portable-tgs"
|
||||
: /^ai-layer-(rf-detr|object-distance)-/.test(id) ? "portable-objects" : "portable-semantic" }),
|
||||
options);
|
||||
}
|
||||
|
||||
export function useLocalLabStorage(enabled = true) {
|
||||
const [data, setData] = useState<LocalLabStorage | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const refresh = useCallback(async () => {
|
||||
try { setData(await request()); setError(null); }
|
||||
catch (reason) { setError(reason instanceof Error ? reason.message : "Хранилище недоступно."); }
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
void refresh();
|
||||
const update = () => void refresh();
|
||||
window.addEventListener("focus", update);
|
||||
window.addEventListener("lab-local-storage-changed", update);
|
||||
const interval = window.setInterval(update, 15000);
|
||||
return () => {
|
||||
window.clearInterval(interval);
|
||||
window.removeEventListener("focus", update);
|
||||
window.removeEventListener("lab-local-storage-changed", update);
|
||||
};
|
||||
}, [enabled, refresh]);
|
||||
return { data, error, refresh };
|
||||
}
|
||||
export function announceLabStorageChange() {
|
||||
window.dispatchEvent(new Event("lab-local-storage-changed"));
|
||||
}
|
||||
Reference in New Issue
Block a user