feat: add configurable GFS retention per orbit

This commit is contained in:
2026-11-10 11:16:03 +07:00
parent 749c4cc828
commit 30a1a9b8f0
14 changed files with 665 additions and 86 deletions

View File

@@ -247,7 +247,7 @@ export default function App() {
<SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane>
)}
{mode === "decay" && (
<SpringPane key="decay"><DecayView appliedPresets={sceneOrbits.map((orbit) => orbit.decay_preset ?? "week-of-dailies")} /></SpringPane>
<SpringPane key="decay"><DecayView orbits={sceneOrbits} /></SpringPane>
)}
{mode === "snapshot" && (
<SpringPane key="snapshot">

View File

@@ -15,16 +15,25 @@ export type Orbit = {
dry_run: boolean;
schedule?: string | null;
decay_preset?: string;
retention?: RetentionPolicy | null;
};
export type RetentionPolicy = {
keep_daily: number;
keep_weekly: number;
keep_monthly: number;
keep_yearly: number;
};
export type RetentionSettings = { decay_preset: string } | { retention: RetentionPolicy };
export type CreateOrbitInput = {
name: string;
provider: "filesystem" | "postgres";
paths: string[];
schedule?: string;
decay_preset: string;
dry_run: boolean;
};
} & RetentionSettings;
async function request(path: string, init?: RequestInit): Promise<Response> {
const r = await fetch(path, init);
@@ -64,12 +73,20 @@ export async function createOrbit(input: CreateOrbitInput): Promise<Orbit> {
provider: input.provider,
provider_config: { paths: input.paths },
schedule: input.schedule || null,
decay_preset: input.decay_preset,
...("retention" in input ? { retention: input.retention } : { decay_preset: input.decay_preset }),
dry_run: input.dry_run,
}),
});
}
export async function updateOrbitRetention(id: string, settings: RetentionSettings): Promise<void> {
await api(`/api/v1/orbits/${id}/retention`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(settings),
});
}
export async function startPairing(): Promise<{ code: string; expires_at: string }> {
return api("/api/v1/wormhole/pairing", { method: "POST" });
}

View File

@@ -1,21 +1,24 @@
import type { Orbit } from "../../api";
import { DECAY_PRESETS } from "../../lib/format";
import { describeRetention } from "../orbits/RetentionFields";
import { Hint } from "../ui/EmptyState";
import { TelemetryPanel } from "../ui/Telemetry";
export function DecayView({ appliedPresets }: { appliedPresets: string[] }) {
const unique = [...new Set(appliedPresets)];
export function DecayView({ orbits }: { orbits: Orbit[] }) {
const appliedPresets = new Set(orbits.filter((orbit) => !orbit.retention).map((orbit) => orbit.decay_preset ?? DECAY_PRESETS[0].id));
const custom = orbits.filter((orbit) => orbit.retention);
return (
<div className="h-full overflow-y-auto px-4 py-4 pb-28">
<h2 className="text-2xl font-semibold text-star-100">Decay</h2>
<p className="text-sm text-star-300 mt-1 mb-6">
Old snapshots fade on purpose — friendly presets, not retention spreadsheets.
Choose a preset or set daily, weekly, monthly and yearly counts for each orbit.
</p>
<span className="text-xs text-star-400">Presets — pick one when you create an orbit</span>
<span className="text-xs text-star-400">Retention presets</span>
<ul className="space-y-3 mt-3">
{DECAY_PRESETS.map((p) => {
const active = unique.includes(p.id);
const active = appliedPresets.has(p.id);
return (
<li
key={p.id}
@@ -39,6 +42,20 @@ export function DecayView({ appliedPresets }: { appliedPresets: string[] }) {
})}
</ul>
{custom.length > 0 && (
<div className="mt-4 space-y-2">
<h3 className="text-sm font-medium text-star-100">Custom policies</h3>
<ul className="space-y-2">
{custom.map((orbit) => (
<li key={orbit.id} className="rounded-2xl border border-space-700 bg-space-800/40 p-4">
<p className="text-sm font-medium text-star-100">{orbit.name}</p>
<p className="text-sm text-star-400">{describeRetention(orbit)}</p>
</li>
))}
</ul>
</div>
)}
<Hint>
Decay runs after a successful capture — rehearsed orbits never prune the vault.
</Hint>

View File

@@ -2,8 +2,9 @@ import { useState, type ReactNode } from "react";
import { AnimatePresence } from "motion/react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Orbit } from "../../api";
import { createOrbit } from "../../api";
import { DECAY_PRESETS, orbitStatus, schedulePhrase } from "../../lib/format";
import { createOrbit, updateOrbitRetention } from "../../api";
import { orbitStatus, schedulePhrase } from "../../lib/format";
import { describeRetention, retentionDraft, RetentionFields, retentionSettings } from "./RetentionFields";
import { Button } from "../ui/Button";
import { OrbitStatusDot } from "../ui/StatusDot";
import { TelemetryPanel } from "../ui/Telemetry";
@@ -22,20 +23,24 @@ export function OrbitsView({
const qc = useQueryClient();
const [name, setName] = useState("nightly-docs");
const [path, setPath] = useState("./docs");
const [preset, setPreset] = useState<string>(DECAY_PRESETS[0].id);
const [retention, setRetention] = useState(() => retentionDraft());
const [editingRetention, setEditingRetention] = useState<string | null>(null);
const [rehearse, setRehearse] = useState(false);
const [schedule, setSchedule] = useState("0 2 * * *");
const create = useMutation({
mutationFn: () =>
createOrbit({
mutationFn: () => {
const settings = retentionSettings(retention);
if (!settings) throw new Error("Invalid retention policy");
return createOrbit({
name,
provider: "filesystem",
paths: [path],
schedule: schedule || undefined,
decay_preset: preset,
...settings,
dry_run: rehearse,
}),
});
},
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["orbits"] });
setEditing(false);
@@ -58,6 +63,7 @@ export function OrbitsView({
<h3 className="font-semibold text-star-100 truncate">{o.name}</h3>
<p className="text-sm text-star-300">{orbitStatus(o.last_status).label}</p>
<p className="text-xs text-star-400 mt-0.5">{schedulePhrase(o.schedule, o.dry_run)}</p>
<p className="text-xs text-star-400 mt-0.5">{describeRetention(o)}</p>
{o.dry_run && (
<span className="inline-block mt-2 text-[10px] uppercase tracking-wider text-orbit-amber border border-orbit-amber/30 rounded px-2 py-0.5">
Rehearse mode
@@ -74,7 +80,12 @@ export function OrbitsView({
>
{o.dry_run ? "Rehearse" : "Capture now"}
</Button>
<Button className="flex-1 text-xs py-2" onClick={() => setEditingRetention(o.id)}
disabled={editingRetention === o.id}>
Edit retention
</Button>
</div>
{editingRetention === o.id && <OrbitRetentionEditor orbit={o} onClose={() => setEditingRetention(null)} />}
<TelemetryPanel>
{JSON.stringify(o, null, 2)}
</TelemetryPanel>
@@ -112,20 +123,7 @@ export function OrbitsView({
onChange={(e) => setSchedule(e.target.value)}
/>
</label>
<label className="block text-sm">
<span className="text-star-400">Decay</span>
<select
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2"
value={preset}
onChange={(e) => setPreset(e.target.value)}
>
{DECAY_PRESETS.map((p) => (
<option key={p.id} value={p.id}>
{p.title}
</option>
))}
</select>
</label>
<RetentionFields draft={retention} onChange={setRetention} />
<label className="flex items-center gap-2 text-sm text-star-300">
<input type="checkbox" checked={rehearse} onChange={(e) => setRehearse(e.target.checked)} />
Rehearse only (dry run)
@@ -141,7 +139,7 @@ export function OrbitsView({
<Button
variant="primary"
className="flex-1"
disabled={create.isPending}
disabled={create.isPending || !retentionSettings(retention)}
onClick={() => create.mutate()}
>
Save orbit
@@ -161,3 +159,30 @@ export function OrbitsView({
</div>
);
}
function OrbitRetentionEditor({ orbit, onClose }: { orbit: Orbit; onClose: () => void }) {
const [draft, setDraft] = useState(() => retentionDraft(orbit));
const settings = retentionSettings(draft);
const qc = useQueryClient();
const save = useMutation({
mutationFn: updateOrbitRetention.bind(null, orbit.id),
onSuccess: async () => {
await qc.invalidateQueries({ queryKey: ["orbits"] });
onClose();
},
});
return (
<form className="mt-4 space-y-3 border-t border-space-700 pt-3" onSubmit={(e) => {
e.preventDefault();
if (settings && !save.isPending) save.mutate(settings);
}}>
<RetentionFields draft={draft} onChange={setDraft} />
<Hint>Changes apply after the next successful capture.</Hint>
{save.isError && <p role="alert" className="text-sm text-orbit-red">Retention could not be saved.</p>}
<div className="flex gap-2">
<Button type="button" className="flex-1" disabled={save.isPending} onClick={onClose}>Cancel</Button>
<Button type="submit" variant="primary" className="flex-1" disabled={!settings || save.isPending}>Save retention</Button>
</div>
</form>
);
}

View File

@@ -0,0 +1,80 @@
import type { Orbit, RetentionPolicy, RetentionSettings } from "../../api";
import { DECAY_PRESETS } from "../../lib/format";
const tiers = [
["keep_daily", "Daily"],
["keep_weekly", "Weekly"],
["keep_monthly", "Monthly"],
["keep_yearly", "Yearly"],
] as const;
const maxCount = 4_294_967_295;
const inputClass = "mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2";
type Draft = { preset: string; counts: Record<keyof RetentionPolicy, string> };
export function retentionDraft(orbit?: Orbit): Draft {
return {
preset: orbit?.retention ? "custom" : orbit?.decay_preset ?? DECAY_PRESETS[0].id,
counts: {
keep_daily: String(orbit?.retention?.keep_daily ?? 7),
keep_weekly: String(orbit?.retention?.keep_weekly ?? 2),
keep_monthly: String(orbit?.retention?.keep_monthly ?? 6),
keep_yearly: String(orbit?.retention?.keep_yearly ?? 3),
},
};
}
export function retentionSettings({ preset, counts }: Draft): RetentionSettings | undefined {
if (preset !== "custom") return { decay_preset: preset };
const retention: RetentionPolicy = { keep_daily: 0, keep_weekly: 0, keep_monthly: 0, keep_yearly: 0 };
for (const [key] of tiers) {
const count = Number(counts[key]);
if (counts[key] === "" || !Number.isInteger(count) || count < 0 || count > maxCount) return;
retention[key] = count;
}
if (Object.values(retention).some((count) => count > 0)) return { retention };
}
export function describeRetention(orbit: Orbit): string {
if (orbit.retention) {
const policy = orbit.retention;
return tiers.map(([key, label]) => `${policy[key]} ${label.toLowerCase()}`).join(" · ");
}
const preset = orbit.decay_preset ?? DECAY_PRESETS[0].id;
return DECAY_PRESETS.find((item) => item.id === preset)?.title ?? preset;
}
export function RetentionFields({ draft, onChange }: { draft: Draft; onChange: (draft: Draft) => void }) {
const invalid = !retentionSettings(draft);
return (
<div className="space-y-3">
<label className="block text-sm">
<span className="text-star-400">Retention</span>
<select className={inputClass} value={draft.preset} onChange={(e) => onChange({ ...draft, preset: e.target.value })}>
{!DECAY_PRESETS.some((item) => item.id === draft.preset) && draft.preset !== "custom" && (
<option value={draft.preset}>{draft.preset}</option>
)}
{DECAY_PRESETS.map((preset) => <option key={preset.id} value={preset.id}>{preset.title}</option>)}
<option value="custom">Custom (GFS)</option>
</select>
</label>
{draft.preset === "custom" && (
<fieldset className="space-y-2">
<legend className="text-sm text-star-400">Snapshots to keep</legend>
<div className="grid grid-cols-2 gap-2">
{tiers.map(([key, label]) => (
<label key={key} className="block min-w-0 text-sm text-star-300">
{label}
<input className={inputClass} type="number" inputMode="numeric" min={0} max={maxCount} step={1}
value={draft.counts[key]}
onChange={(e) => onChange({ ...draft, counts: { ...draft.counts, [key]: e.target.value } })} />
</label>
))}
</div>
<p className="text-xs text-star-400">Zero skips a tier. The newest snapshot in each UTC period can count toward several tiers.</p>
{invalid && <p role="alert" className="text-xs text-orbit-red">Enter whole numbers from 0 to 4,294,967,295, with at least one above zero.</p>}
</fieldset>
)}
</div>
);
}