feat(controlplane): field-level sys_audit table, audit view on settings pages, whole-task time limit

This commit is contained in:
sam committed 2026-09-25 09:54:30 +10:00
1 parent 49d7527f1c
commit 8fea8e8686
43 files changed
+1176 -174

No files matched your search

+129
View File
@@ -0,0 +1,129 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Table,
TableBody,
TableCell,
TableEmpty,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { ago } from "@/lib/format";
import {
useControlPlaneStore,
type AuditEntry,
type ResourceDescriptor,
} from "@/stores/control-plane";
/**
* The field-level audit of the settings a page shows: one row per changed
* field, newest first. Restore puts a resource back to the version before a
* change, as an ordinary replace, so the restore is audited like any edit.
*/
const props = defineProps<{ resources: ResourceDescriptor[] }>();
const store = useControlPlaneStore();
const entries = ref<AuditEntry[]>([]);
const error = ref("");
const kinds = computed(() => props.resources.map((r) => r.kind));
const titles = computed(
() => new Map(props.resources.map((r) => [r.kind, r.title])),
);
// Every stored version on the page: a save anywhere refreshes the list.
const versions = computed(() =>
kinds.value.map((kind) => store.stateFor(kind).resource?.version).join(","),
);
async function load(): Promise<void> {
if (!kinds.value.length) return;
try {
entries.value = await store.audit("resources", kinds.value);
error.value = "";
} catch (err) {
error.value = String((err as Error).message || err);
}
}
watch([kinds, versions], load, { immediate: true });
function show(value: unknown): string {
return value === null || value === undefined ? "" : JSON.stringify(value);
}
async function restoreBefore(entry: AuditEntry): Promise<void> {
const previous = (await store.history(entry.record_key)).find(
(revision) => revision.version === entry.version - 1,
);
if (previous) await store.replace(entry.record_key, previous.value);
}
</script>
<template>
<Card class="mb-4">
<CardHeader><CardTitle>Audit</CardTitle></CardHeader>
<CardContent>
<p v-if="error" class="text-sm text-destructive" role="alert">
{{ error }}
</p>
<Table v-else>
<TableHeader>
<TableRow>
<TableHead>When</TableHead>
<TableHead>Setting</TableHead>
<TableHead>Field</TableHead>
<TableHead>Old value</TableHead>
<TableHead>New value</TableHead>
<TableHead>Version</TableHead>
<TableHead>Changed by</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="entry in entries" :key="entry.id">
<TableCell class="whitespace-nowrap" :title="entry.at">{{
entry.at ? ago(entry.at) : ""
}}</TableCell>
<TableCell>{{
titles.get(entry.record_key) || entry.record_key
}}</TableCell>
<TableCell class="font-mono text-xs">{{
entry.field || "(whole value)"
}}</TableCell>
<TableCell
class="max-w-64 truncate font-mono text-xs text-fg-muted"
:title="show(entry.old_value)"
>{{ show(entry.old_value) }}</TableCell
>
<TableCell
class="max-w-64 truncate font-mono text-xs"
:title="show(entry.new_value)"
>{{ show(entry.new_value) }}</TableCell
>
<TableCell>{{ entry.version }}</TableCell>
<TableCell class="whitespace-nowrap"
>{{ entry.actor
}}<span class="text-fg-muted"> · {{ entry.source }}</span></TableCell
>
<TableCell>
<Button
v-if="entry.version > 1"
variant="ghost"
size="sm"
:disabled="store.stateFor(entry.record_key).saving"
@click="restoreBefore(entry)"
>Restore</Button
>
</TableCell>
</TableRow>
<TableEmpty v-if="!entries.length" :colspan="8"
>No changes recorded yet.</TableEmpty
>
</TableBody>
</Table>
</CardContent>
</Card>
</template>
+2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import AuditTable from "@/base/AuditTable.vue";
import { computed, onMounted, ref } from "vue";
import { storeToRefs } from "pinia";
@@ -68,5 +69,6 @@ onMounted(() => Promise.all([load(), controlPlane.load()]));
:key="descriptor.kind"
:descriptor="descriptor"
/>
<AuditTable :resources="settings" />
</div>
</template>
-107
View File
@@ -1,107 +0,0 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import { RotateCcw } from "@lucide/vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { ago } from "@/lib/format";
import {
useControlPlaneStore,
type ResourceRevision,
} from "@/stores/control-plane";
/**
* A resource's audit trail, and the way back to any earlier value.
*
* Restoring is not its own command: a revision carries the value it held, so
* putting it back is an ordinary replace against the version currently stored.
* That keeps the restore in the same history as every other edit rather than
* rewriting the past.
*
* The list loads when it is opened. A settings page that nobody is auditing
* should not pay for the query on every render.
*/
const props = defineProps<{ kind: string }>();
const store = useControlPlaneStore();
const state = computed(() => store.stateFor(props.kind));
const revisions = ref<ResourceRevision[]>([]);
const open = ref(false);
const loading = ref(false);
const error = ref("");
async function load(): Promise<void> {
loading.value = true;
error.value = "";
try {
revisions.value = await store.history(props.kind);
} catch (err) {
error.value = String((err as Error).message || err);
} finally {
loading.value = false;
}
}
async function toggle(): Promise<void> {
open.value = !open.value;
if (open.value) await load();
}
async function restore(revision: ResourceRevision): Promise<void> {
if (await store.replace(props.kind, revision.value)) await load();
}
</script>
<template>
<div class="mt-5 border-t border-border pt-4">
<Button variant="ghost" size="sm" :aria-expanded="open" @click="toggle">
<Spinner v-if="loading" data-icon="inline-start" />
{{ open ? "Hide history" : "History" }}
</Button>
<p v-if="error" class="mt-2 text-sm text-destructive" role="alert">
{{ error }}
</p>
<div v-else-if="open && !loading" class="mt-3">
<p v-if="!revisions.length" class="text-sm text-muted-foreground">
No changes recorded yet.
</p>
<ul v-else class="space-y-1">
<li
v-for="revision in revisions"
:key="revision.version"
class="grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 border-t border-border py-2 first:border-t-0"
>
<Badge
:variant="
revision.version === state.resource?.version ? 'ok' : 'idle'
"
>v{{ revision.version }}</Badge
>
<span
class="min-w-0 truncate text-sm text-fg-muted"
:title="`${revision.actor} via ${revision.source}`"
>
{{ revision.actor }}
<span class="text-fg-subtle">via {{ revision.source }}</span>
<span v-if="revision.at" class="text-fg-subtle">
· {{ ago(revision.at) }}</span
>
</span>
<Button
v-if="revision.version !== state.resource?.version"
variant="outline"
size="sm"
:disabled="state.saving"
:title="`Replace the current value with version ${revision.version}`"
@click="restore(revision)"
>
<RotateCcw /> Restore
</Button>
</li>
</ul>
</div>
</div>
</template>
@@ -10,7 +10,6 @@ import {
type ResourceDescriptor,
} from "@/stores/control-plane";
import ConfigCard from "./ConfigCard.vue";
import ResourceHistory from "./ResourceHistory.vue";
import StructuredValueEditor from "./StructuredValueEditor.vue";
import { parseSchema } from "./resource-schema";
@@ -75,6 +74,5 @@ async function save(): Promise<void> {
</Button>
</div>
</form>
<ResourceHistory :kind="descriptor.kind" />
</ConfigCard>
</template>
+2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import AuditTable from "@/base/AuditTable.vue";
import { computed, onMounted } from "vue";
import { storeToRefs } from "pinia";
@@ -32,6 +33,7 @@ onMounted(load);
:key="descriptor.kind"
:descriptor="descriptor"
/>
<AuditTable :resources="resources" />
<ConfigCard title="Managed elsewhere">
<div class="flex flex-wrap gap-2">
<Button as-child variant="outline"
+2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import AuditTable from "@/base/AuditTable.vue";
import { computed, onMounted } from "vue";
import { storeToRefs } from "pinia";
@@ -27,5 +28,6 @@ onMounted(controlPlane.load);
descriptor.kind === 'provider-settings' ? 'providers' : 'roles'
"
/>
<AuditTable :resources="resources" />
</div>
</template>
+2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import AuditTable from "@/base/AuditTable.vue";
import { computed, onMounted } from "vue";
import { storeToRefs } from "pinia";
@@ -27,5 +28,6 @@ onMounted(controlPlane.load);
:descriptor="descriptor"
root-path="repositories"
/>
<AuditTable :resources="resources" />
</div>
</template>
+2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import AuditTable from "@/base/AuditTable.vue";
import { computed, onMounted } from "vue";
import { storeToRefs } from "pinia";
@@ -25,5 +26,6 @@ onMounted(controlPlane.load);
:key="descriptor.kind"
:descriptor="descriptor"
/>
<AuditTable :resources="resources" />
</div>
</template>
+24
View File
@@ -99,6 +99,20 @@ export interface ResourceRevision {
at?: string;
}
/** One changed field of one record, as sys_audit holds it. */
export interface AuditEntry {
id: number;
table: string;
record_key: string;
field: string;
old_value: unknown;
new_value: unknown;
version: number;
actor: string;
source: string;
at?: string;
}
interface HistoryResponse {
revisions?: ResourceRevision[];
}
@@ -365,6 +379,15 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
return response.revisions ?? [];
}
async function audit(table: string, keys: string[]): Promise<AuditEntry[]> {
const query = new URLSearchParams({ table });
for (const key of keys) query.append("key", key);
const response = await request<{ entries?: AuditEntry[] }>(
`/api/control-plane/audit?${query}`,
);
return response.entries ?? [];
}
/** The shipped definitions the catalog offers as "restore shipped". */
function shippedWorkflows(): WorkflowDefinitionCollection {
const defaults = catalog.value.find(
@@ -384,6 +407,7 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
catalogError,
states,
genericResources,
audit,
history,
load,
loadApplyStatus,
+24 -1
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { computed } from "vue";
import { useIntervalFn } from "@vueuse/core";
import { computed, ref } from "vue";
import {
Empty,
@@ -13,6 +14,8 @@ import AttemptSelector from "./AttemptSelector.vue";
import PanelError from "./PanelError.vue";
import PanelLoading from "./PanelLoading.vue";
import StageRow from "./StageRow.vue";
import { selectConfigEvent, taskTimeLimitMs } from "./attempt-config";
import { duration } from "./timeline-event";
import { stageStatusMeta } from "./stage-rail";
import { useTaskRun } from "./use-task-run";
import type { AttemptsState, Stage } from "./task-run";
@@ -61,6 +64,23 @@ function selectStage(stage: Stage): void {
run.setTab("log");
}
const now = ref(new Date());
useIntervalFn(() => (now.value = new Date()), 30_000);
const limitMs = computed(() =>
taskTimeLimitMs(selectConfigEvent(run.events, attempt.value?.attempt ?? null)),
);
/** Time used is shown only while the attempt runs: once it ends, the stage
* durations are the record, and wall time since the start is not work. */
const timeLimit = computed(() => {
if (!limitMs.value) return "";
const limit = duration(limitMs.value);
const started = Date.parse(attempt.value?.started_at ?? "");
if (attempt.value?.status !== "running" || Number.isNaN(started)) {
return `${limit} time limit`;
}
return `${duration(Math.max(0, now.value.getTime() - started))} used of ${limit} limit`;
});
/** An attempt's start is rendered as an absolute instant, never as "started 2
* days ago": on a still-running attempt a relative stamp reads as two days of
* work, which is exactly the elapsed-time claim the design forbids. */
@@ -108,6 +128,9 @@ const startedAt = computed(() => {
</template>
<Badge :variant="meta.kind">{{ meta.label }}</Badge>
<span class="text-xs text-fg-muted">{{ startedAt }}</span>
<span v-if="timeLimit" class="text-xs text-fg-muted">{{
timeLimit
}}</span>
</div>
<ol
v-if="stages.length"
+25
View File
@@ -25,3 +25,28 @@ export function selectConfigEvent(
) || null
);
}
const GO_DURATION_UNITS: Record<string, number> = {
h: 3600_000,
m: 60_000,
s: 1000,
ms: 1,
};
/**
* The whole-task time limit the attempt ran under, in milliseconds, from its
* captured config. The daemon writes it as a Go duration ("4h0m0s"); 0 means
* no limit or none recorded.
*/
export function taskTimeLimitMs(event: unknown): number {
const document = (event as { data?: { document?: unknown } } | null)?.data
?.document as { budgets?: { task_wall_clock?: unknown } } | undefined;
const value = document?.budgets?.task_wall_clock;
if (typeof value !== "string") return 0;
const parts = [...value.matchAll(/(\d+(?:\.\d+)?)(ms|h|m|s)/g)];
if (!parts.length || parts.map((p) => p[0]).join("") !== value) return 0;
return parts.reduce(
(total, [, n, unit]) => total + Number(n) * GO_DURATION_UNITS[unit],
0,
);
}