feat(copies): add verified space-saving copies

Offer same-volume hard links for sampled 2.61.0.43 resources after checking their content and keeping mutable files independent. Support converting existing copies and detach registered links during version updates.
This commit is contained in:
N0VAN0M4LY committed 2026-11-30 05:51:22 +08:00
1 parent 0881d62766
commit 2a97b0d46c
22 files changed
+3118 -111

No files matched your search

@@ -1,6 +1,5 @@
import { createHash } from 'node:crypto';
import { createReadStream } from 'node:fs';
import { copyFile, mkdir, readdir, rm } from 'node:fs/promises';
import type { BigIntStats } from 'node:fs';
import { copyFile, lstat, mkdir, readdir, rm } from 'node:fs/promises';
import { dirname, isAbsolute, join, normalize, parse, relative } from 'node:path';
import { app } from 'electron';
import { compareVersions, GAME_FILES, isInSteamLibrary } from '@wto/patcher';
@@ -8,7 +7,9 @@ import { AppError } from '@shared/errors.ts';
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { sameVolume } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts';
import { fileHash, hardlinkResource, hasHardlinkEvidence, linkVerifiedResource, sameResource, verifyHardlinkResource } from '../install/hardlink-files.ts';
import { installationInProgress } from '../install/install-game.ts';
import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, updateCopyRecord } from '../install/install-record.ts';
import { checkPatches } from '../install/patch-check.ts';
@@ -30,7 +31,11 @@ export function cancelMaintenance(): void {
export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
const record = await requireCopy(id);
const source = await readSource(record);
return { sourceVersion: source?.version ?? null, updateAvailable: isNewer(source, record.gameVersion) };
return {
sourceVersion: source?.version ?? null,
updateAvailable: isNewer(source, record.gameVersion),
spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath),
};
}
export async function maintainCopy(
@@ -38,7 +43,10 @@ export async function maintainCopy(
publish: (progress: MaintenanceProgress) => void,
): Promise<Copies> {
if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
const job = { stop: new AbortController(), interruptible: request.operation === 'update' };
const job = {
stop: new AbortController(),
interruptible: request.operation === 'update' || request.operation === 'compact',
};
current = job;
const signal = job.stop.signal;
const report = (phase: MaintenanceProgress['phase'], doneBytes = 0, totalBytes = 0): void => {
@@ -60,6 +68,8 @@ export async function maintainCopy(
return await repair(record, root, () => report('applying'));
case 'update':
return await updateFromSource(record, root, signal, report);
case 'compact':
return await compactCopy(record, root, signal, report);
case 'delete':
report('applying');
return await remove(record, root, request.deleteData);
@@ -154,13 +164,15 @@ async function updateFromSource(record: InstallRecord, root: string, signal: Abo
const plan = await planCopy(game.path);
const inventory = plan.files.map((entry) => entry.relativePath);
const found = new Set(inventory.map(key));
const remove = (record.sourceFiles ?? []).filter((name) => !found.has(key(name)));
const linked = record.hardlinkedFiles ?? [];
const linkedPaths = new Set(linked.map(key));
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name)));
const changed: CopyPlan['files'][number][] = [];
for (const file of plan.files) {
signal.throwIfAborted();
const target = await scopedInstallFile(dataPath, root, file.relativePath);
const old = await fileInfo(target);
if (!old?.isFile() || old.size !== file.bytes) {
if (linkedPaths.has(key(file.relativePath)) || !old?.isFile() || old.size !== file.bytes) {
changed.push(file);
} else if (Math.trunc(old.mtimeMs) !== Math.trunc(file.modifiedAt)) {
const [targetHash, sourceHash] = await Promise.all([
@@ -206,6 +218,7 @@ async function updateFromSource(record: InstallRecord, root: string, signal: Abo
}, () => updateCopyRecord(record.id, (latest) => ({
...latest, gameVersion: game.version, unavailablePatches: check.unavailable,
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
...(linked.length ? { hardlinkedFiles: [] } : {}),
})));
}
@@ -223,10 +236,68 @@ async function scopedInstallFile(dataPath: string, root: string, name: string):
return target;
}
async function fileHash(path: string, signal: AbortSignal): Promise<string> {
const hash = createHash('sha256');
for await (const bytes of createReadStream(path, { signal })) hash.update(bytes as Buffer);
return hash.digest('hex');
async function convertibleCopy(record: InstallRecord, source: GameFolderInspection, root: string): Promise<boolean> {
return record.method === 'copy' && source.version === record.gameVersion &&
hasHardlinkEvidence(source.version) && await sameVolume(source.path, root);
}
async function compactCopy(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
const source = await readSource(record);
if (!source || !await convertibleCopy(record, source, root) ||
(await inspectGameFolder(root)).version !== source.version) {
throw new AppError('hardlink_unavailable');
}
const plan = await planCopy(source.path);
const candidates = plan.files.flatMap(({ relativePath, bytes }) => {
const evidence = hardlinkResource(source.version, relativePath, bytes);
return evidence ? [{ relativePath, evidence }] : [];
});
const total = candidates.reduce((bytes, file) => bytes + file.evidence.bytes, 0);
const dataPath = await canonicalCopyPath(record.dataPath);
const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path]));
return changeCopyFiles(root, async (incoming) => {
const replacements: string[] = [];
const unchanged = new Map<string, BigIntStats>();
let checked = 0;
let matches = 0;
let lastReport = 0;
report('checking', 0, total);
for (const { relativePath, evidence } of candidates) {
const target = await scopedInstallFile(dataPath, root, relativePath);
const original = join(source.path, relativePath);
const copyStamp = await verifyHardlinkResource(target, evidence, signal);
const sourceStamp = copyStamp ? await verifyHardlinkResource(original, evidence, signal) : null;
if (copyStamp && sourceStamp) {
if (!sameResource(copyStamp, sourceStamp)) {
const staged = join(incoming, relativePath);
await mkdir(dirname(staged), { recursive: true });
const stagedStamp = await linkVerifiedResource(original, staged, sourceStamp);
unchanged.set(target, copyStamp);
unchanged.set(staged, stagedStamp);
replacements.push(relativePath);
}
linked.set(key(relativePath), relativePath);
matches += 1;
}
checked += evidence.bytes;
if (checked === total || Date.now() - lastReport >= 250) {
lastReport = Date.now();
report('checking', checked, total);
}
}
if (!matches) throw new AppError('hardlink_no_match');
signal.throwIfAborted();
if ((await readSource(record))?.version !== source.version) throw new AppError('hardlink_file_changed');
for (const [path, stamp] of unchanged) {
signal.throwIfAborted();
if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
}
signal.throwIfAborted();
report('applying', total, total);
return { replace: replacements, remove: [] };
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
}
async function stageBackup(folder: string, file: string, target: string): Promise<void> {
@@ -1,26 +1,11 @@
import { lstat, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import type { FolderSize } from '@shared/schemas/install.ts';
import { planCopy } from '../install/copy-game.ts';
import { hardlinkResource } from '../install/hardlink-files.ts';
/**
* The size of a folder tree, counted the way the copy will copy it: regular files only. Links
* and junctions are not followed. Asynchronous, so the window stays responsive on a large
* installation.
*/
export async function measureFolder(root: string): Promise<FolderSize> {
let bytes = 0;
let files = 0;
const pending = [root];
while (pending.length) {
const folder = pending.pop()!;
for (const entry of await readdir(folder, { withFileTypes: true })) {
const path = join(folder, entry.name);
if (entry.isDirectory()) pending.push(path);
else if (entry.isFile()) {
bytes += (await lstat(path)).size;
files += 1;
}
}
}
return { bytes, files };
/** Estimate the installation size and the bytes eligible for content verification. */
export async function measureFolder(root: string, version?: string | null): Promise<FolderSize> {
const plan = await planCopy(root);
const linkableBytes = plan.files.reduce((total, file) =>
total + (hardlinkResource(version, file.relativePath, file.bytes)?.bytes ?? 0), 0);
return { bytes: plan.totalBytes, files: plan.files.length, linkableBytes };
}
@@ -1,5 +1,5 @@
import { readdir, realpath, stat, statfs } from 'node:fs/promises';
import { dirname, parse, relative, resolve, isAbsolute } from 'node:path';
import { dirname, relative, resolve, isAbsolute } from 'node:path';
import { isInSteamLibrary } from '@wto/patcher';
import type { TargetFolderInspection } from '@shared/schemas/install.ts';
@@ -15,10 +15,26 @@ export async function inspectTargetFolder(path: string, stockPath: string): Prom
problem: await targetProblem(target, stock),
inSteamLibrary: isInSteamLibrary(target),
freeBytes: await freeBytes(target),
sameDriveAsStock: parse(target).root.toLowerCase() === parse(stock).root.toLowerCase(),
sameDriveAsStock: await sameVolume(target, stock),
};
}
/** Compare actual volumes, including directories reached through junctions. */
export async function sameVolume(left: string, right: string): Promise<boolean> {
const [first, second] = await Promise.all([volumeDevice(left), volumeDevice(right)]);
return first !== null && first === second;
}
async function volumeDevice(path: string): Promise<bigint | null> {
for (let folder = resolve(path); ; folder = dirname(folder)) {
try {
return (await stat(folder, { bigint: true })).dev || null;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || dirname(folder) === folder) return null;
}
}
}
async function targetProblem(target: string, stock: string): Promise<TargetFolderInspection['problem']> {
if (contains(stock, target) || contains(target, stock)) return 'overlaps_stock';
let entries: string[];
@@ -39,7 +55,7 @@ function contains(outer: string, inner: string): boolean {
}
/** Free bytes on the drive of the nearest existing folder at or above `path`. */
async function freeBytes(path: string): Promise<number | null> {
export async function freeBytes(path: string): Promise<number | null> {
for (let folder = path; ; folder = dirname(folder)) {
try {
const info = await statfs(folder);
@@ -1,8 +1,10 @@
import { createReadStream, createWriteStream } from 'node:fs';
import { createReadStream, createWriteStream, type BigIntStats } from 'node:fs';
import { lstat, mkdir, readdir, rm, utimes } from 'node:fs/promises';
import { join, relative } from 'node:path';
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { AppError } from '@shared/errors.ts';
import { linkVerifiedResource, sameResource } from './hardlink-files.ts';
/**
* Copy a War Thunder installation into a new or empty folder (install method "copy"). The stock
@@ -72,9 +74,11 @@ export async function copyPlannedFiles(
plan: CopyPlan,
signal: AbortSignal,
onProgress: (progress: CopyProgress) => void,
hardlinks?: ReadonlyMap<string, BigIntStats>,
): Promise<void> {
await mkdir(target, { recursive: true });
for (const folder of plan.folders) await mkdir(join(target, folder), { recursive: true });
const linkedTargets = hardlinks ? new Map<string, BigIntStats>() : undefined;
let next = 0;
let doneBytes = 0;
let doneFiles = 0;
@@ -94,15 +98,24 @@ export async function copyPlannedFiles(
while (next < plan.files.length) {
stopSignal.throwIfAborted();
const file = plan.files[next++]!;
await pipeline(
createReadStream(join(source, file.relativePath)),
countBytes(),
// 'wx': fail instead of overwriting a file that is already there.
createWriteStream(join(target, file.relativePath), { flags: 'wx' }),
{ signal: stopSignal },
);
const modified = new Date(file.modifiedAt);
await utimes(join(target, file.relativePath), modified, modified);
const from = join(source, file.relativePath);
const to = join(target, file.relativePath);
const verified = hardlinks?.get(file.relativePath);
if (verified) {
const linked = await linkVerifiedResource(from, to, verified);
linkedTargets?.set(to, linked);
doneBytes += file.bytes;
} else {
await pipeline(
createReadStream(from),
countBytes(),
// 'wx': fail instead of overwriting a file that is already there.
createWriteStream(to, { flags: 'wx' }),
{ signal: stopSignal },
);
const modified = new Date(file.modifiedAt);
await utimes(to, modified, modified);
}
doneFiles += 1;
onProgress({ doneBytes, doneFiles });
}
@@ -114,6 +127,12 @@ export async function copyPlannedFiles(
const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext));
const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');
if (failed) throw failed.reason;
if (linkedTargets) {
for (const [path, stamp] of linkedTargets) {
signal.throwIfAborted();
if (!sameResource(stamp, await lstat(path, { bigint: true }))) throw new AppError('hardlink_file_changed');
}
}
}
/**
@@ -0,0 +1,70 @@
import { createHash } from 'node:crypto';
import { createReadStream, type BigIntStats } from 'node:fs';
import { link, lstat } from 'node:fs/promises';
import { AppError } from '@shared/errors.ts';
import evidence from './hardlink-resources-2.61.0.43.json' with { type: 'json' };
interface ResourceEvidence {
readonly bytes: number;
readonly sha256: string;
}
const resources: Readonly<Record<string, ResourceEvidence>> = evidence.files;
export function hasHardlinkEvidence(version: string | null | undefined): boolean {
return version === evidence.gameVersion;
}
/** Only an exact path and size from the sampled build can be offered as a candidate. */
export function hardlinkResource(
version: string | null | undefined,
relativePath: string,
bytes: number,
): ResourceEvidence | undefined {
if (!hasHardlinkEvidence(version)) return undefined;
const path = relativePath.replaceAll('\\', '/').toLowerCase();
const resource = Object.hasOwn(resources, path) ? resources[path] : undefined;
return resource?.bytes === bytes ? resource : undefined;
}
export async function fileHash(path: string, signal: AbortSignal): Promise<string> {
const hash = createHash('sha256');
for await (const chunk of createReadStream(path, { signal })) hash.update(chunk as Buffer);
return hash.digest('hex');
}
/** Read the measured bytes and retain the observed file identity until the link is created. */
export async function verifyHardlinkResource(
path: string,
resource: ResourceEvidence,
signal: AbortSignal,
): Promise<BigIntStats | null> {
signal.throwIfAborted();
const before = await lstat(path, { bigint: true }).catch((error: NodeJS.ErrnoException) => {
if (error.code === 'ENOENT') return null;
throw error;
});
if (!before?.isFile() || before.size !== BigInt(resource.bytes)) return null;
const checksum = await fileHash(path, signal);
const after = await lstat(path, { bigint: true });
if (!sameResource(before, after)) throw new AppError('hardlink_file_changed');
return checksum === resource.sha256 ? after : null;
}
export function sameResource(left: BigIntStats, right: BigIntStats): boolean {
return sameIdentityAndContents(left, right) && left.ctimeNs === right.ctimeNs;
}
export async function linkVerifiedResource(source: string, target: string, verified: BigIntStats): Promise<BigIntStats> {
if (!sameResource(verified, await lstat(source, { bigint: true }))) throw new AppError('hardlink_file_changed');
await link(source, target);
// Linking may change ctime. The inode, contents and modification time must stay the same.
const linked = await lstat(target, { bigint: true });
if (!sameIdentityAndContents(verified, linked)) throw new AppError('hardlink_file_changed');
return linked;
}
function sameIdentityAndContents(left: BigIntStats, right: BigIntStats): boolean {
return right.isFile() && left.dev === right.dev && left.ino === right.ino &&
left.size === right.size && left.mtimeNs === right.mtimeNs;
}
File diff suppressed because it is too large. Load diff
@@ -1,10 +1,13 @@
import type { BigIntStats } from 'node:fs';
import { access, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { AppError } from '@shared/errors.ts';
import type { InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { inspectTargetFolder } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, removeInterruptedCopy } from './copy-game.ts';
import { requireAvailableCopy, writeInstallRecord } from './install-record.ts';
import { freeBytes, inspectTargetFolder, sameVolume } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, removeInterruptedCopy, type CopyPlan } from './copy-game.ts';
import { hardlinkResource, hasHardlinkEvidence, verifyHardlinkResource } from './hardlink-files.ts';
import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts';
import { checkPatches } from './patch-check.ts';
import { backUpStockFiles, stockBackupPath } from './stock-backup.ts';
@@ -35,6 +38,9 @@ export async function installGame(request: InstallRequest, onProgress: (progress
running = controller;
try {
return await install(request, controller.signal, throttled(onProgress));
} catch (error) {
if (controller.signal.aborted) throw new AppError('install_cancelled');
throw error;
} finally {
running = null;
}
@@ -75,6 +81,13 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, gameFolder) : null;
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
const useHardLinks = request.method === 'copy' && request.useHardLinks === true;
if (useHardLinks) {
if (!target?.sameDriveAsStock || !hasHardlinkEvidence(game.version)) throw new AppError('hardlink_unavailable');
if (copyPathContains(await canonicalCopyPath(gameFolder), await canonicalCopyPath(request.dataPath))) {
throw new AppError('target_not_usable', { problem: 'overlaps_stock' });
}
}
const inSteamLibrary = target ? target.inSteamLibrary : game.inSteamLibrary;
if (inSteamLibrary && !request.steamLibraryConfirmed) throw new AppError('steam_library_not_confirmed');
@@ -86,8 +99,8 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
if (check.unavailable.length && !request.missingFeaturesAccepted) throw new AppError('missing_features_not_accepted');
signal.throwIfAborted();
const sourceFiles = request.method === 'copy'
? await copyGame(request.sourcePath, copyPath, target!.freeBytes, signal, report)
const copied = request.method === 'copy'
? await copyGame(request.sourcePath, copyPath, target!.freeBytes, useHardLinks ? game.version : null, signal, report)
: undefined;
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
@@ -106,7 +119,7 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
unavailablePatches: check.unavailable,
installedAt: new Date().toISOString(),
lastCheckedAt: new Date().toISOString(),
...(sourceFiles ? { sourceFiles } : {}),
...copied,
};
await writeInstallRecord(record);
return record;
@@ -115,29 +128,70 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
async function copyGame(
source: string,
target: string,
freeBytes: number | null,
initialFreeBytes: number | null,
hardlinkVersion: string | null,
signal: AbortSignal,
report: (progress: InstallProgress) => void,
): Promise<string[]> {
): Promise<Pick<InstallRecord, 'sourceFiles' | 'hardlinkedFiles'>> {
report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const plan = await planCopy(source);
if (freeBytes !== null && freeBytes < plan.totalBytes + SPARE_BYTES) {
throw new AppError('not_enough_space', { neededGb: gigabytes(plan.totalBytes + SPARE_BYTES), freeGb: gigabytes(freeBytes) });
const hardlinks = hardlinkVersion ? await confirmHardlinks(source, hardlinkVersion, plan, signal, report) : undefined;
const linkedBytes = hardlinks ? [...hardlinks.values()].reduce((total, file) => total + Number(file.size), 0) : 0;
const neededBytes = plan.totalBytes - linkedBytes + SPARE_BYTES;
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== hardlinkVersion)) {
throw new AppError('hardlink_file_changed');
}
const available = hardlinks ? await freeBytes(target) : initialFreeBytes;
if (available !== null && available < neededBytes) {
throw new AppError('not_enough_space', { neededGb: gigabytes(neededBytes), freeGb: gigabytes(available) });
}
const targetExisted = await exists(target);
const totals = { totalBytes: plan.totalBytes, totalFiles: plan.files.length };
report({ phase: 'copying', doneBytes: 0, doneFiles: 0, ...totals });
try {
await copyPlannedFiles(source, target, plan, signal, (done) => report({ phase: 'copying', ...done, ...totals }));
return plan.files.map((file) => file.relativePath);
await copyPlannedFiles(source, target, plan, signal,
(done) => report({ phase: 'copying', ...done, ...totals }), hardlinks);
if (hardlinks && (await inspectGameFolder(source)).version !== hardlinkVersion) throw new AppError('hardlink_file_changed');
return {
sourceFiles: plan.files.map((file) => file.relativePath),
...(hardlinks ? { hardlinkedFiles: [...hardlinks.keys()] } : {}),
};
} catch (error) {
await removeInterruptedCopy(target, targetExisted).catch((cleanup) => console.error('[install] removing the interrupted copy failed:', cleanup));
if (signal.aborted) throw new AppError('install_cancelled');
if (error instanceof AppError) throw error;
console.error('[install] copying failed:', error);
throw new AppError('copy_failed');
}
}
async function confirmHardlinks(
source: string,
version: string,
plan: CopyPlan,
signal: AbortSignal,
report: (progress: InstallProgress) => void,
): Promise<ReadonlyMap<string, BigIntStats>> {
const candidates = plan.files.flatMap((file) => {
const evidence = hardlinkResource(version, file.relativePath, file.bytes);
return evidence ? [{ path: file.relativePath, evidence }] : [];
});
const totalBytes = candidates.reduce((total, file) => total + file.evidence.bytes, 0);
const links = new Map<string, BigIntStats>();
let doneBytes = 0;
let doneFiles = 0;
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
for (const { path, evidence } of candidates) {
const verified = await verifyHardlinkResource(join(source, path), evidence, signal);
if (verified) links.set(path, verified);
doneBytes += evidence.bytes;
doneFiles += 1;
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
}
if (!links.size) throw new AppError('hardlink_no_match');
return links;
}
async function requireGameFolder(path: string) {
const game = await inspectGameFolder(path);
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path });