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
254 lines
7.7 KiB
TypeScript
254 lines
7.7 KiB
TypeScript
// Client de l'API : le serveur Go relaie /api/garage/v2/... vers l'API d'administration de Garage.
|
|
|
|
export class ApiError extends Error {
|
|
status: number;
|
|
constructor(status: number, message: string) {
|
|
super(message);
|
|
this.status = status;
|
|
}
|
|
}
|
|
|
|
async function req<T>(url: string, init: RequestInit = {}): Promise<T> {
|
|
const r = await fetch(url, {
|
|
...init,
|
|
credentials: "same-origin",
|
|
headers: { "X-Requested-With": "garage-ui", ...(init.body ? { "Content-Type": "application/json" } : {}) },
|
|
});
|
|
const text = await r.text();
|
|
let data: unknown = null;
|
|
try {
|
|
data = text ? JSON.parse(text) : null;
|
|
} catch {
|
|
data = text;
|
|
}
|
|
if (!r.ok) {
|
|
const d = data as { message?: string; error?: string } | string | null;
|
|
const msg = (d && typeof d === "object" ? d.message || d.error : d) || r.statusText;
|
|
throw new ApiError(r.status, String(msg));
|
|
}
|
|
return data as T;
|
|
}
|
|
|
|
const qs = (p?: Record<string, string | number | boolean | undefined>) => {
|
|
const u = new URLSearchParams();
|
|
for (const [k, v] of Object.entries(p ?? {})) if (v !== undefined && v !== "") u.set(k, String(v));
|
|
const s = u.toString();
|
|
return s ? `?${s}` : "";
|
|
};
|
|
|
|
type Params = Record<string, string | number | boolean | undefined>;
|
|
|
|
export const garage = {
|
|
get: <T>(op: string, params?: Params) => req<T>(`/api/garage/v2/${op}${qs(params)}`),
|
|
post: <T = unknown>(op: string, params?: Params, body?: unknown) =>
|
|
req<T>(`/api/garage/v2/${op}${qs(params)}`, { method: "POST", body: JSON.stringify(body ?? {}) }),
|
|
};
|
|
|
|
// --- Types (partiels : seuls les champs utilisés) ---------------------------------
|
|
|
|
export interface Perm {
|
|
read: boolean;
|
|
write: boolean;
|
|
owner: boolean;
|
|
}
|
|
|
|
export interface BucketListItem {
|
|
id: string;
|
|
created: string;
|
|
globalAliases: string[];
|
|
localAliases: { accessKeyId: string; alias: string }[];
|
|
}
|
|
|
|
export interface BucketKey {
|
|
accessKeyId: string;
|
|
name: string;
|
|
permissions: Perm;
|
|
bucketLocalAliases?: string[];
|
|
}
|
|
|
|
export interface BucketInfo extends BucketListItem {
|
|
websiteAccess: boolean;
|
|
websiteConfig?: { indexDocument?: string; errorDocument?: string } | null;
|
|
keys: BucketKey[];
|
|
objects: number;
|
|
bytes: number;
|
|
unfinishedUploads: number;
|
|
unfinishedMultipartUploads: number;
|
|
unfinishedMultipartUploadParts: number;
|
|
unfinishedMultipartUploadBytes: number;
|
|
quotas: { maxSize?: number | null; maxObjects?: number | null };
|
|
}
|
|
|
|
export interface KeyListItem {
|
|
id: string;
|
|
name: string;
|
|
created?: string;
|
|
expiration?: string | null;
|
|
expired?: boolean;
|
|
}
|
|
|
|
export interface KeyInfo {
|
|
accessKeyId: string;
|
|
name: string;
|
|
created?: string;
|
|
expiration?: string | null;
|
|
expired?: boolean;
|
|
secretAccessKey?: string | null;
|
|
permissions: { createBucket: boolean };
|
|
buckets: { id: string; globalAliases: string[]; localAliases: string[]; permissions: Perm }[];
|
|
}
|
|
|
|
export interface NodeInfo {
|
|
id: string;
|
|
role?: { zone: string; tags: string[]; capacity: number | null } | null;
|
|
addr?: string | null;
|
|
hostname?: string | null;
|
|
isUp: boolean;
|
|
lastSeenSecsAgo?: number | null;
|
|
draining?: boolean;
|
|
dataPartition?: { available: number; total: number } | null;
|
|
metadataPartition?: { available: number; total: number } | null;
|
|
garageVersion?: string | null;
|
|
}
|
|
|
|
export interface ClusterStatus {
|
|
layoutVersion: number;
|
|
nodes: NodeInfo[];
|
|
}
|
|
|
|
export interface ClusterHealth {
|
|
status: string;
|
|
knownNodes: number;
|
|
connectedNodes: number;
|
|
storageNodes: number;
|
|
storageNodesUp: number;
|
|
partitions: number;
|
|
partitionsQuorum: number;
|
|
partitionsAllOk: number;
|
|
}
|
|
|
|
export interface LayoutRole {
|
|
id: string;
|
|
zone: string;
|
|
tags: string[];
|
|
capacity: number | null;
|
|
}
|
|
|
|
export interface StagedRole {
|
|
id: string;
|
|
remove?: boolean;
|
|
zone?: string;
|
|
tags?: string[];
|
|
capacity?: number | null;
|
|
}
|
|
|
|
export interface ClusterLayout {
|
|
version: number;
|
|
roles: LayoutRole[];
|
|
parameters?: { zoneRedundancy?: unknown };
|
|
partitionSize?: number;
|
|
stagedRoleChanges: StagedRole[];
|
|
}
|
|
|
|
/** Réponse d'une opération diffusée aux nœuds (?node=*). */
|
|
export interface MultiResponse<T> {
|
|
success: Record<string, T>;
|
|
error: Record<string, string>;
|
|
}
|
|
|
|
export interface Config {
|
|
title: string;
|
|
version: string;
|
|
auth: boolean;
|
|
user: string;
|
|
cli: boolean;
|
|
s3Endpoint: string;
|
|
s3Region: string;
|
|
}
|
|
|
|
export const appApi = {
|
|
config: () => req<Config>("/api/config"),
|
|
login: (user: string, password: string) => req<{ user: string }>("/api/login", { method: "POST", body: JSON.stringify({ user, password }) }),
|
|
logout: () => req("/api/logout", { method: "POST", body: "{}" }),
|
|
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);
|
|
|
|
/**
|
|
* GetBucketInfo, normalisé : Garage 2.x ne renvoie pas `localAliases` au niveau du bucket (ils sont
|
|
* dans `keys[].bucketLocalAliases`) et peut omettre d'autres champs ; l'interface n'a ainsi jamais
|
|
* à tester leur présence.
|
|
*/
|
|
export async function getBucket(id: string): Promise<BucketInfo> {
|
|
const b = await garage.get<Partial<BucketInfo>>("GetBucketInfo", { id });
|
|
const keys = b.keys ?? [];
|
|
return {
|
|
id: b.id ?? id,
|
|
created: b.created ?? "",
|
|
globalAliases: b.globalAliases ?? [],
|
|
localAliases: b.localAliases ?? keys.flatMap((k) => (k.bucketLocalAliases ?? []).map((alias) => ({ accessKeyId: k.accessKeyId, alias }))),
|
|
websiteAccess: !!b.websiteAccess,
|
|
websiteConfig: b.websiteConfig ?? null,
|
|
keys,
|
|
objects: b.objects ?? 0,
|
|
bytes: b.bytes ?? 0,
|
|
unfinishedUploads: b.unfinishedUploads ?? 0,
|
|
unfinishedMultipartUploads: b.unfinishedMultipartUploads ?? 0,
|
|
unfinishedMultipartUploadParts: b.unfinishedMultipartUploadParts ?? 0,
|
|
unfinishedMultipartUploadBytes: b.unfinishedMultipartUploadBytes ?? 0,
|
|
quotas: b.quotas ?? {},
|
|
};
|
|
}
|
|
|
|
export const errMsg = (e: unknown) => (e instanceof Error ? e.message : String(e));
|