// 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(url: string, init: RequestInit = {}): Promise { 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) => { 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; export const garage = { get: (op: string, params?: Params) => req(`/api/garage/v2/${op}${qs(params)}`), post: (op: string, params?: Params, body?: unknown) => req(`/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 { success: Record; error: Record; } export interface Config { title: string; version: string; auth: boolean; user: string; cli: boolean; s3Endpoint: string; s3Region: string; } export const appApi = { config: () => req("/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 { 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 { const b = await garage.get>("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));