Buckets : bouton Vider (objets et envois multipart inachevés)

L'API d'administration ne sait pas supprimer d'objets : le serveur passe
par l'API S3 avec une clé temporaire (CreateKey + AllowBucketKey),
supprime les objets par lots de 1000 (ListObjectsV2 + DeleteObjects,
signature v4 en bibliothèque standard), nettoie les envois inachevés
(CleanupIncompleteUploads, olderThanSecs 0) puis supprime la clé.
Avancement diffusé en NDJSON (POST /api/buckets/empty?id=...).
Confirmation par saisie du nom, interruption et reprise possibles.
Nouvelle variable GARAGE_S3_API_URL (défaut : hôte admin, port 3900).
Mock : API S3 minimale sur :3900. Tests : signature (exemple AWS) et
vidage complet simulé.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LNfwm2bSk3o3YKYUP5P691
This commit is contained in:
claude BotandClaude Opus 5.5 committed 2026-11-27 12:15:50 +01:00
1 parent ea2058b6c1
commit e21ef321f9
7 files changed
+278 -8

No files matched your search

+115 -5
View File
@@ -1,9 +1,9 @@
import { useState } from "react";
import { garage, getBucket, bucketName, type BucketInfo, type BucketListItem, type KeyListItem, type Perm } from "./api";
import { useRef, useState } from "react";
import { garage, getBucket, bucketName, emptyBucket, errMsg, type BucketInfo, type EmptyProgress, type BucketListItem, type KeyListItem, type Perm } from "./api";
import { GIB, fmtDate, fmtNum, fmtSize } from "./format";
import { BucketIcon, GlobeIcon } from "./gicons";
import { CloseIcon, PlusIcon, RefreshIcon, TrashIcon } from "./icons";
import { Confirm, CopyButton, Loading, Modal, Mono, PageHead, Status, UsageBar, useAct, useLoad } from "./ui";
import { CloseIcon, PlusIcon, RefreshIcon, TrashFullIcon, TrashIcon } from "./icons";
import { Confirm, CopyButton, Loading, Modal, Mono, PageHead, Status, UsageBar, useAct, useLoad, useNotify } from "./ui";
// --- Liste -------------------------------------------------------------------------
@@ -138,6 +138,7 @@ export function BucketPage({ id }: { id: string }) {
const { data: b, error, loading, reload } = useLoad(() => getBucket(id), [id]);
const keys = useLoad(() => garage.get<KeyListItem[]>("ListKeys"), []);
const [confirmDelete, setConfirmDelete] = useState(false);
const [emptying, setEmptying] = useState(false);
const [alias, setAlias] = useState("");
const [addKey, setAddKey] = useState("");
@@ -152,6 +153,14 @@ export function BucketPage({ id }: { id: string }) {
return (
<div className="page">
<PageHead title={name} back={{ href: "#/buckets", label: "Buckets" }}>
<button
className="danger-outline"
onClick={() => setEmptying(true)}
disabled={b.objects === 0 && b.unfinishedMultipartUploads === 0}
title={b.objects === 0 && b.unfinishedMultipartUploads === 0 ? "Le bucket est déjà vide" : "Supprimer tous les objets du bucket"}
>
<TrashFullIcon /> Vider
</button>
<button className="danger-outline" onClick={() => setConfirmDelete(true)}>
<TrashIcon /> Supprimer
</button>
@@ -291,12 +300,29 @@ export function BucketPage({ id }: { id: string }) {
</button>
</section>
{emptying && (
<EmptyBucket
b={b}
onClose={() => {
setEmptying(false);
reload();
}}
/>
)}
{confirmDelete && (
<Confirm
title="Supprimer le bucket"
message={
<p>
Le bucket <strong>{name}</strong> sera supprimé définitivement. Garage refuse de supprimer un bucket qui contient encore des objets.
Le bucket <strong>{name}</strong> sera supprimé définitivement. Garage refuse de supprimer un bucket qui contient encore des objets
{b.objects > 0 && (
<>
{" "}
: celui-ci en contient <strong>{fmtNum(b.objects)}</strong>, videz-le d'abord (bouton « Vider »)
</>
)}
.
</p>
}
confirmLabel="Supprimer"
@@ -312,6 +338,90 @@ export function BucketPage({ id }: { id: string }) {
);
}
/** Vidage : confirmation par saisie du nom, puis avancement lot par lot. */
function EmptyBucket({ b, onClose }: { b: BucketInfo; onClose: () => void }) {
const notify = useNotify();
const name = bucketName(b);
const [typed, setTyped] = useState("");
const [p, setP] = useState<EmptyProgress | null>(null);
const [running, setRunning] = useState(false);
const [error, setError] = useState("");
const abort = useRef<AbortController | null>(null);
const finished = p?.phase === "done";
// Le compteur d'objets de Garage est approximatif (mis à jour en tâche de fond) : borné à 99 % avant la fin.
const pct = finished ? 100 : Math.min(99, Math.round(((p?.deleted ?? 0) / Math.max(b.objects, 1)) * 100));
const start = async () => {
setRunning(true);
setError("");
abort.current = new AbortController();
try {
const r = await emptyBucket(b.id, setP, abort.current.signal);
notify(`Bucket « ${name} » vidé : ${fmtNum(r.deleted)} objets supprimés`, r.failed ? undefined : "ok");
} catch (e) {
setError(abort.current.signal.aborted ? "Vidage interrompu." : errMsg(e));
} finally {
setRunning(false);
}
};
const close = () => {
if (running && !confirm("Interrompre le vidage en cours ? Les objets déjà supprimés le restent.")) return;
abort.current?.abort();
onClose();
};
return (
<Modal title="Vider le bucket" onClose={close} small>
<div className="modal-text">
<p>
Tous les objets du bucket <strong>{name}</strong> ({fmtNum(b.objects)} objets, {fmtSize(b.bytes)}) seront supprimés définitivement, ainsi que les envois
multipart inachevés. Le bucket, ses alias, clés, quotas et réglages sont conservés.
</p>
<p className="muted small-text">
Garage n'a pas de versioning S3 ni de corbeille : cette action est irréversible. L'interface passe par l'API S3 avec une clé temporaire, supprimée à la fin.
</p>
</div>
{!p && !running && (
<label className="field" style={{ marginTop: "0.8rem" }}>
<span>
Tapez <code>{name}</code> pour confirmer
</span>
<input type="text" value={typed} onChange={(e) => setTyped(e.target.value)} autoFocus autoComplete="off" />
</label>
)}
{(p || running) && (
<div style={{ marginTop: "0.8rem" }}>
<div className="bar" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
<span style={{ width: `${pct}%` }} />
</div>
<p className="small-text">
{finished ? "Terminé :" : p?.phase === "uploads" ? "Nettoyage des envois inachevés…" : "Suppression en cours…"} {fmtNum(p?.deleted ?? 0)} objets supprimés
{p?.failed ? `, ${fmtNum(p.failed)} en échec` : ""}
{finished && p?.uploadsDeleted ? `, ${fmtNum(p.uploadsDeleted)} envois inachevés nettoyés` : ""}.
</p>
{p?.errors?.length ? (
<ul className="small-text muted">
{p.errors.map((e) => (
<li key={e}>{e}</li>
))}
</ul>
) : null}
</div>
)}
{error && <p className="small-text" style={{ color: "var(--danger)" }}>{error}</p>}
<div className="modal-actions">
<span className="spacer" />
<button onClick={close}>{finished ? "Fermer" : running ? "Interrompre" : "Annuler"}</button>
{!finished && (
<button className="danger-fill" disabled={typed !== name || running} onClick={start}>
{error ? "Reprendre" : "Vider"}
</button>
)}
</div>
</Modal>
);
}
function QuotaForm({ b, onSave }: { b: BucketInfo; onSave: (q: { maxSize: number | null; maxObjects: number | null }) => void }) {
const [size, setSize] = useState(b.quotas?.maxSize ? String(+(b.quotas.maxSize / GIB).toFixed(2)) : "");
const [objs, setObjs] = useState(b.quotas?.maxObjects ? String(b.quotas.maxObjects) : "");
+48
View File
@@ -173,6 +173,54 @@ export const appApi = {
cli: (args: string[]) => req<{ exitCode: number; output: string; ms: number }>("/api/cli", { method: "POST", body: JSON.stringify({ args }) }),
};
/** Avancement du vidage d'un bucket (une ligne NDJSON par lot de 1000 objets). */
export interface EmptyProgress {
phase: "start" | "objects" | "uploads" | "done" | "error";
deleted: number;
failed: number;
uploadsDeleted?: number;
errors?: string[];
message?: string;
}
/**
* Vide un bucket (objets puis envois multipart inachevés). Le serveur passe par l'API S3 avec une
* clé temporaire, et diffuse l'avancement : onProgress est appelé à chaque lot.
*/
export async function emptyBucket(id: string, onProgress: (p: EmptyProgress) => void, signal?: AbortSignal): Promise<EmptyProgress> {
const r = await fetch(`/api/buckets/empty${qs({ id })}`, { method: "POST", credentials: "same-origin", headers: { "X-Requested-With": "garage-ui" }, signal });
if (!r.ok || !r.body) {
let msg = r.statusText;
try {
msg = (await r.json()).message || msg;
} catch {
/* réponse non JSON */
}
throw new ApiError(r.status, msg);
}
const reader = r.body.getReader();
const dec = new TextDecoder();
let buf = "";
let last: EmptyProgress | null = null;
for (;;) {
const { value, done } = await reader.read();
if (value) buf += dec.decode(value, { stream: true });
let nl;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (!line) continue;
last = JSON.parse(line) as EmptyProgress;
onProgress(last);
}
if (done) break;
}
if (!last) throw new ApiError(502, "Réponse vide du serveur");
if (last.phase === "error") throw new ApiError(502, last.message || "Échec du vidage");
if (last.phase !== "done") throw new ApiError(502, `Vidage interrompu après ${last.deleted} objets supprimés`);
return last;
}
export const bucketName = (b: { id: string; globalAliases?: string[]; localAliases?: { alias: string }[] }) =>
b.globalAliases?.[0] ?? b.localAliases?.[0]?.alias ?? b.id.slice(0, 12);