Files
glenloch-media/src/lib/event-nfs-archive.ts
T
2026-11-20 04:07:02 +00:00

261 lines
7.8 KiB
TypeScript

/**
* Archive an event's bytes to a mounted NFS destination.
*
* The archive is written to a temporary sibling directory and renamed into
* place only after every original, every saved edit, and the manifest have
* landed. Callers delete the live event only after this function succeeds.
*/
import { randomUUID } from "node:crypto";
import { copyFile, mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { assignArchivePaths } from "./event-archive";
import {
editedPhotoFilename,
eventPhotoPath,
sanitizePhotoFilename,
} from "./event-photos";
export class EventArchiveError extends Error {
constructor(message: string) {
super(message);
this.name = "EventArchiveError";
}
}
export interface ArchivePhotoInput {
id: string;
folderId: string;
folderName: string;
filename: string;
kind: "raw" | "image";
sizeBytes: number;
storedName: string;
editedStoredName: string | null;
editedSizeBytes: number | null;
editJson: string | null;
}
export interface ArchiveEventInput {
eventId: string;
title: string;
startsAt: Date;
endsAt: Date | null;
location: string | null;
description: string | null;
archivePath: string;
archiveFolder: string;
nfsShare: string;
photos: readonly ArchivePhotoInput[];
}
export interface ArchiveEventResult {
archivePath: string;
files: number;
bytes: number;
}
function slugify(value: string): string {
return value
.normalize("NFKC")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60);
}
/** `2026-11-19-easter-outreach-a1b2c3d4`; stable and human-readable. */
export function archiveDirectoryName(
title: string,
startsAt: Date,
eventId: string,
): string {
const date = startsAt.toISOString().slice(0, 10);
const slug = slugify(title) || "event";
const suffix = eventId.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 8) || "event";
return `${date}-${slug}-${suffix}`;
}
function archiveRoot(input: ArchiveEventInput): string {
if (!path.isAbsolute(input.archivePath)) {
throw new EventArchiveError("The archive path must be absolute.");
}
const root = path.resolve(input.archivePath);
const folder = sanitizePhotoFilename(input.archiveFolder)
.replace(/^\.+/, "")
.replace(/\.+$/, "")
.trim();
if (!folder) throw new EventArchiveError("The archive folder name is empty.");
const resolved = path.resolve(root, folder);
if (resolved !== root && !resolved.startsWith(`${root}${path.sep}`)) {
throw new EventArchiveError("The archive folder escapes the mounted path.");
}
return resolved;
}
function safeRelative(partial: string, relative: string): string {
const destination = path.resolve(partial, relative);
if (
destination !== partial &&
!destination.startsWith(`${partial}${path.sep}`)
) {
throw new EventArchiveError("An archive entry escaped the destination.");
}
return destination;
}
async function ensureUniqueDestination(
basePath: string,
name: string,
): Promise<string> {
for (let copy = 1; copy < 1000; copy += 1) {
const candidate = path.join(
basePath,
copy === 1 ? name : `${name}-${copy}`,
);
try {
await stat(candidate);
} catch {
return candidate;
}
}
throw new EventArchiveError("Could not find a free archive folder name.");
}
/**
* Copy originals + saved edits and write a manifest. Missing source bytes abort
* the archive instead of producing a partial backup that would make deleting
* the event unsafe.
*/
export async function archiveEventPhotos(
input: ArchiveEventInput,
): Promise<ArchiveEventResult> {
const root = archiveRoot(input);
await mkdir(root, { recursive: true });
const baseName = archiveDirectoryName(input.title, input.startsAt, input.eventId);
const destination = await ensureUniqueDestination(root, baseName);
const partial = `${destination}.partial-${randomUUID()}`;
const entries: {
photo: ArchivePhotoInput;
originalRelative: string;
editedRelative: string | null;
originalSource: string;
editedSource: string | null;
}[] = [];
const originalPaths = assignArchivePaths(
input.photos.map((photo) => ({
id: `${photo.id}:original`,
folderName: photo.folderName,
filename: photo.filename,
})),
);
const editedPaths = assignArchivePaths(
input.photos
.filter((photo) => photo.editedStoredName)
.map((photo) => ({
id: `${photo.id}:edited`,
folderName: photo.folderName,
filename: editedPhotoFilename(photo.filename),
})),
);
// Preflight every source before creating the destination. This is what makes
// "archive succeeded, then delete the event" safe.
for (const photo of input.photos) {
const originalSource = eventPhotoPath(photo.storedName);
const originalInfo = await stat(originalSource).catch(() => null);
if (!originalInfo?.isFile()) {
throw new EventArchiveError(
`Original ${photo.filename} is missing from storage; the event was not removed.`,
);
}
let editedSource: string | null = null;
if (photo.editedStoredName) {
editedSource = eventPhotoPath(photo.editedStoredName);
const editedInfo = await stat(editedSource).catch(() => null);
if (!editedInfo?.isFile()) {
throw new EventArchiveError(
`Saved edit for ${photo.filename} is missing from storage; the event was not removed.`,
);
}
}
entries.push({
photo,
originalRelative: `Originals/${originalPaths.get(`${photo.id}:original`)!}`,
editedRelative: photo.editedStoredName
? `Edited/${editedPaths.get(`${photo.id}:edited`)!}`
: null,
originalSource,
editedSource,
});
}
let files = 0;
let bytes = 0;
try {
await mkdir(partial, { recursive: true });
for (const entry of entries) {
const originalDestination = safeRelative(
partial,
entry.originalRelative,
);
await mkdir(path.dirname(originalDestination), { recursive: true });
await copyFile(entry.originalSource, originalDestination);
files += 1;
bytes += entry.photo.sizeBytes;
if (entry.editedRelative && entry.editedSource) {
const editedDestination = safeRelative(partial, entry.editedRelative);
await mkdir(path.dirname(editedDestination), { recursive: true });
await copyFile(entry.editedSource, editedDestination);
const editedInfo = await stat(editedDestination);
files += 1;
bytes += editedInfo.size;
}
}
const manifest = {
event: {
id: input.eventId,
title: input.title,
startsAt: input.startsAt.toISOString(),
endsAt: input.endsAt?.toISOString() ?? null,
location: input.location,
description: input.description,
},
archivedAt: new Date().toISOString(),
nfsShare: input.nfsShare || null,
archiveFolder: input.archiveFolder,
photos: entries.map((entry) => ({
id: entry.photo.id,
folder: entry.photo.folderName,
filename: entry.photo.filename,
kind: entry.photo.kind,
sizeBytes: entry.photo.sizeBytes,
original: entry.originalRelative,
edited: entry.editedRelative,
editedSizeBytes: entry.photo.editedSizeBytes,
editJson: entry.photo.editJson,
})),
};
await writeFile(
path.join(partial, "manifest.json"),
JSON.stringify(manifest, null, 2),
"utf8",
);
files += 1;
await rename(partial, destination);
return { archivePath: destination, files, bytes };
} catch (error) {
await rm(partial, { recursive: true, force: true }).catch(() => undefined);
if (error instanceof EventArchiveError) throw error;
const detail = error instanceof Error ? error.message : "unknown error";
throw new EventArchiveError(`The archive could not be written: ${detail}`);
}
}