import { defineStore } from "pinia"; import { ref } from "vue"; import { errors } from "@/copy/errors"; import { ApiError, api, describeError, type QueryParams } from "@/lib/api"; import { apiParams, dedupeRecords, emptyFacets, recordKey, type AuditFacets, type AuditQuery, type AuditRecord, type AuditResponse, } from "./audit"; const PAGE_SIZE = 100; function failure(err: unknown): string { if (err instanceof ApiError && err.status === 503) return errors.audit.unavailable; return describeError(err, errors.audit.load); } /** The server's vocabularies arrive with the first page; a later page that * omits one must not blank the filters the operator is using. */ function facetsFrom(next: AuditFacets | undefined, current: AuditFacets): AuditFacets { if (!next) return current; const pick = (incoming: T[] | undefined, previous: T[]): T[] => incoming?.length ? incoming : previous; return { categories: pick(next.categories, current.categories), severities: pick(next.severities, current.severities), outcomes: pick(next.outcomes, current.outcomes), target_kinds: pick(next.target_kinds, current.target_kinds), settings_kinds: pick(next.settings_kinds, current.settings_kinds), retention_kinds: pick(next.retention_kinds, current.retention_kinds), }; } /** One loaded audit feed. Filters live in the URL; this store owns only the * pages fetched for the current filter. */ export const useAuditStore = defineStore("audit", () => { const records = ref([]); const facets = ref(emptyFacets()); const loading = ref(false); const loadingMore = ref(false); const error = ref(""); const moreError = ref(""); const nextCursor = ref(null); const hasMore = ref(false); let generation = 0; let pages = 1; // Resolved once per filter load: the cursor is bound to these exact bounds. let params: QueryParams = {}; async function load(query: AuditQuery): Promise { const token = ++generation; params = apiParams(query); loading.value = true; loadingMore.value = false; error.value = ""; moreError.value = ""; records.value = []; nextCursor.value = null; hasMore.value = false; pages = 1; try { const response = await api.audit({ ...params, limit: PAGE_SIZE }); if (token !== generation) return; records.value = dedupeRecords(response.records ?? []); facets.value = facetsFrom(response.facets, facets.value); nextCursor.value = response.next_cursor || null; hasMore.value = !!response.has_more; } catch (err) { if (token !== generation) return; error.value = failure(err); } finally { if (token === generation) loading.value = false; } } async function loadMore(): Promise { if (!nextCursor.value || loading.value || loadingMore.value) return; const token = generation; loadingMore.value = true; moreError.value = ""; try { const response = await api.audit({ ...params, cursor: nextCursor.value, limit: PAGE_SIZE, }); if (token !== generation) return; records.value = dedupeRecords([...records.value, ...(response.records ?? [])]); nextCursor.value = response.next_cursor || null; hasMore.value = !!response.has_more; pages += 1; } catch (err) { if (token === generation) moreError.value = failure(err); } finally { if (token === generation) loadingMore.value = false; } } /** Merges a fresh page one into the loaded feed: an id already on screen * keeps its place, replaced when the server now sends different content (a * coalesced denial count, say). An unseen id is returned so the page can * prepend it or hold it behind the new-events button. */ function mergePageOne(incoming: AuditRecord[]): AuditRecord[] { const positions = new Map(records.value.map((record, index) => [recordKey(record), index])); const merged = records.value.slice(); const added: AuditRecord[] = []; let replaced = false; for (const record of dedupeRecords(incoming)) { const at = positions.get(recordKey(record)); if (at === undefined) { added.push(record); continue; } if (JSON.stringify(merged[at]) === JSON.stringify(record)) continue; merged[at] = record; replaced = true; } if (replaced) records.value = merged; return added; } /** Re-reads page one after a live head. Returns the records this page did * not already hold; the page decides whether to prepend or hold them. */ async function refresh(): Promise { if (loading.value || error.value) return []; const token = generation; const response = await api.audit({ ...params, limit: PAGE_SIZE }); if (token !== generation) return []; facets.value = facetsFrom(response.facets, facets.value); // Only a single-page feed can take the new page-one cursor: a loaded older // page is keyed to the cursor the operator is paging from. if (pages === 1) { nextCursor.value = response.next_cursor || null; hasMore.value = !!response.has_more; } return mergePageOne(response.records ?? []); } function prepend(incoming: AuditRecord[]): void { if (!incoming.length) return; records.value = dedupeRecords([...incoming, ...records.value]); } return { records, facets, loading, loadingMore, error, moreError, nextCursor, hasMore, load, loadMore, refresh, prepend, }; });