Files
archie/ui/src/workflows/use-workflow-stats.ts
T

103 lines
4.1 KiB
TypeScript

import { onMounted, ref, shallowRef } from "vue";
import { toast } from "vue-sonner";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { keepValue } from "@/lib/keep-unchanged";
import { removeWorkflowDefinition, upsertWorkflowDefinition, useWorkflowsStore } from "@/stores/workflows";
import { useLiveResource } from "@/stores/session";
import type { StageStats } from "./WorkflowRuns.vue";
import { setWorkflowField } from "./workflow-edit";
import type { WorkflowDefinition, WorkflowStats } from "./workflow-rows";
interface WorkflowsResponse {
definitions?: WorkflowDefinition[];
workflows?: WorkflowStats[];
stages?: StageStats[];
}
/**
* The workflow list and the workflow page read the same statistics and offer
* the same Enable/Disable and Duplicate, so both take them from here.
*/
export function useWorkflowStats() {
const store = useWorkflowsStore();
const data = shallowRef<WorkflowsResponse>({});
const error = ref<string | null>(null);
const loading = ref(true);
// Statistics are known once a read has returned them; until then, or after a
// failed read, a row says nothing about its runs rather than "Never run".
const statsKnown = ref(false);
// Live reloads and actions overlap; only the newest read may land.
let generation = 0;
async function load() {
const current = ++generation;
try {
// Running count and last status come from the per-workflow statistics: a
// page of the newest tasks would show nothing for a workflow whose runs
// are older than that page.
const response = (await api.workflows<WorkflowsResponse>()) ?? {};
if (current !== generation) return;
data.value = keepValue(data.value, response);
error.value = null;
statsKnown.value = true;
} catch (err) {
if (current === generation) error.value = describeError(err, errors.common.unknown);
} finally {
if (current === generation) loading.value = false;
}
}
useLiveResource("tasks", () => void load(), 5000);
onMounted(() => Promise.all([load(), store.load()]));
// A switch shows the operator's choice at once; the server's answer replaces
// it, or the switch falls back when the change is refused.
const requested = ref<Record<string, boolean>>({});
const enabledOf = (id: string) => requested.value[id] ?? data.value.definitions?.find((d) => d.id === id)?.enabled;
async function setEnabled(id: string, value: boolean) {
requested.value = { ...requested.value, [id]: value };
try {
await api.workflowEnabled(id, value);
toast.success(`${id} ${value ? "enabled" : "disabled"}`);
await load();
} catch (err) {
const reason = describeError(err, errors.common.unknown);
toast.error(value ? errors.workflows.page.notEnabled(id, reason) : errors.workflows.page.notDisabled(id, reason));
} finally {
const rest = { ...requested.value };
delete rest[id];
requested.value = rest;
}
}
/** Saves a copy of a workflow and returns its id, or "" when it was not saved. */
async function duplicate(id: string): Promise<string> {
const stored = store.collection.definitions;
const source = stored.find((d) => d.id === id);
if (!source) return "";
let copy = `${id}-copy`;
for (let n = 2; stored.some((d) => d.id === copy); n++) copy = `${id}-copy-${n}`;
if (await store.save(upsertWorkflowDefinition(store.collection, { id: copy, yaml: setWorkflowField(source.yaml, "id", copy) }))) {
toast.success(`${copy} created`);
return copy;
}
toast.error(errors.workflows.page.notDuplicated(id, store.error || errors.workflows.page.saveFailed));
return "";
}
/** Deletes a workflow and its draft; true when it is gone. */
async function remove(id: string): Promise<boolean> {
if (!(await store.save(removeWorkflowDefinition(store.collection, id)))) {
toast.error(store.error || errors.workflows.page.saveFailed);
return false;
}
await store.putDraft(id, undefined);
toast.success(`${id} deleted`);
return true;
}
return { store, data, error, loading, statsKnown, load, enabledOf, setEnabled, duplicate, remove };
}