feat(launcher): use version-independent rules for space-saving copies

Replace the single-version 2.61.0.43 SHA-256 hardlink manifest with declarative read-only asset rules in packages/patcher/tuning/hardlink-resources.jsonc (content/ and content.hq/ .dxp.bin and .grp archives with no minimum size cutoff). Space-saving installs and conversions now work across minor updates, and updating a space-saving client from a same-volume source preserves or creates hard links instead of detaching them into full copies.
This commit is contained in:
N0VAN0M4LY committed 2026-12-02 17:04:36 +08:00
1 parent 3ed41bdd60
commit bf2ce539e7
14 files changed
+292 -2812

No files matched your search

+2 -2
View File
@@ -70,10 +70,10 @@ export function registerIpcHandlers(): void {
const resolved = await canonicalCopyPath(path);
return { path: resolved, inSteam: isInSteamLibrary(path) || isInSteamLibrary(resolved) };
});
handle('install:measureFolder', async ({ path, version }) => {
handle('install:measureFolder', async ({ path }) => {
await requireFolder(path);
try {
return await measureFolder(path, version);
return await measureFolder(path);
} catch (error) {
console.warn('[install] measuring the folder failed:', error);
throw new AppError('folder_unreadable', { path });
@@ -1,14 +1,22 @@
import type { BigIntStats } from 'node:fs';
import { copyFile, lstat, mkdir } from 'node:fs/promises';
import { dirname, join, normalize } from 'node:path';
import { compareVersions, GAME_FILES } from '@wto/patcher';
import { compareVersions, GAME_FILES, isHardlinkableResource } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceProgress } 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 {
fileHash,
linkVerifiedResource,
sameInode,
sameResource,
statFile,
statHardlinkResource,
verifyMatchingResource,
} from '../install/hardlink-files.ts';
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
import { checkPatches } from '../install/patch-check.ts';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
@@ -40,6 +48,14 @@ export async function repair(record: InstallRecord, root: string, applying: () =
}, listCopies);
}
export async function updatePreservesSpaceSaving(
record: InstallRecord,
source: GameFolderInspection,
root: string,
): Promise<boolean> {
return (record.hardlinkedFiles?.length ?? 0) > 0 && await canShareVolume(source.path, root);
}
export async function updateFromSource(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
const game = await readSource(record);
if (!game || !isNewer(game, record.gameVersion)) throw new AppError('maintenance_no_update');
@@ -50,8 +66,11 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
const found = new Set(inventory.map(key));
const linked = record.hardlinkedFiles ?? [];
const linkedPaths = new Set(linked.map(key));
const preserveHardlinks = await updatePreservesSpaceSaving(record, game, root);
const remove = [...new Set([...(record.sourceFiles ?? []), ...linked])].filter((name) => !found.has(key(name)));
const copy = await planChangedFiles(game.path, root, dataPath, plan, linkedPaths, signal);
const { copy, linksToStage, hardlinkedFiles } = await planUpdateFiles(
game.path, root, dataPath, plan, linkedPaths, preserveHardlinks, signal,
);
for (const file of remove) await scopedInstallFile(dataPath, root, file);
signal.throwIfAborted();
@@ -66,43 +85,86 @@ export async function updateFromSource(record: InstallRecord, root: string, sign
report('copying', doneBytes, copy.totalBytes);
}
});
const stagedLinks = new Map<string, BigIntStats>();
for (const [relativePath, sourceStamp] of linksToStage) {
signal.throwIfAborted();
const staged = join(incoming, relativePath);
await mkdir(dirname(staged), { recursive: true });
const linkedStamp = await linkVerifiedResource(join(game.path, relativePath), staged, sourceStamp);
stagedLinks.set(staged, linkedStamp);
}
const stockFiles = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file));
for (const file of Object.values(GAME_FILES)) {
signal.throwIfAborted();
await stageBackup(game.path, file, join(incoming, STOCK_BACKUP_FOLDER, file));
}
await verifySourceFiles(game.path, plan, signal);
if (stagedLinks.size > 0) await verifyStagedLinks(record, game.version, stagedLinks, signal);
signal.throwIfAborted();
report('applying', copy.totalBytes, copy.totalBytes);
return { replace: [...copy.files.map(({ relativePath }) => relativePath), ...stockFiles], remove };
return {
replace: [...copy.files.map(({ relativePath }) => relativePath), ...linksToStage.keys(), ...stockFiles],
remove,
};
}, () => updateCopyRecord(record.id, (latest) => ({
...latest, gameVersion: game.version, unavailablePatches: check.unavailable,
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
...(linked.length ? { hardlinkedFiles: [] } : {}),
...(preserveHardlinks ? { hardlinkedFiles } : linked.length ? { hardlinkedFiles: [] } : {}),
})));
}
async function planChangedFiles(
source: string, root: string, dataPath: string, plan: CopyPlan, linked: ReadonlySet<string>, signal: AbortSignal,
): Promise<CopyPlan> {
interface UpdateFilePlan {
readonly copy: CopyPlan;
readonly linksToStage: ReadonlyMap<string, BigIntStats>;
readonly hardlinkedFiles: string[];
}
async function planUpdateFiles(
source: string,
root: string,
dataPath: string,
plan: CopyPlan,
linked: ReadonlySet<string>,
preserveHardlinks: boolean,
signal: AbortSignal,
): Promise<UpdateFilePlan> {
const changed: CopyPlan['files'][number][] = [];
const linksToStage = new Map<string, BigIntStats>();
const hardlinkedFiles: string[] = [];
for (const file of plan.files) {
signal.throwIfAborted();
const target = await scopedInstallFile(dataPath, root, file.relativePath);
const old = await fileInfo(target);
if (linked.has(key(file.relativePath)) || !old?.isFile() || old.size !== file.bytes) {
const sourceFile = join(source, file.relativePath);
const old = await statFile(target);
if (preserveHardlinks && isHardlinkableResource(file.relativePath, file.bytes)) {
const sourceStamp = await statHardlinkResource(sourceFile, file.bytes, signal);
if (!sourceStamp) throw new AppError('maintenance_source_changed');
if (!old || !sameResource(old, sourceStamp)) linksToStage.set(file.relativePath, sourceStamp);
hardlinkedFiles.push(file.relativePath);
continue;
}
const sourceStamp = await statFile(sourceFile);
if (!sourceStamp?.isFile() || sourceStamp.size !== BigInt(file.bytes)) {
throw new AppError('maintenance_source_changed');
}
if (linked.has(key(file.relativePath)) || !old?.isFile() || sameInode(old, sourceStamp) ||
old.size !== BigInt(file.bytes)) {
changed.push(file);
} else if (Math.trunc(old.mtimeMs) !== Math.trunc(file.modifiedAt)) {
} else if (Math.trunc(Number(old.mtimeMs)) !== Math.trunc(file.modifiedAt)) {
const [targetHash, sourceHash] = await Promise.all([
fileHash(target, signal), fileHash(join(source, file.relativePath), signal),
fileHash(target, signal), fileHash(sourceFile, signal),
]);
if (targetHash !== sourceHash) changed.push(file);
}
}
return {
files: changed,
folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))],
totalBytes: changed.reduce((total, file) => total + file.bytes, 0),
copy: {
files: changed,
folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))],
totalBytes: changed.reduce((total, file) => total + file.bytes, 0),
},
linksToStage,
hardlinkedFiles,
};
}
@@ -117,8 +179,8 @@ async function verifySourceFiles(source: string, plan: CopyPlan, signal: AbortSi
}
export 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);
return record.method === 'copy' && source.version !== null &&
source.version === record.gameVersion && await canShareVolume(source.path, root);
}
export async function compactCopy(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise<Copies> {
@@ -129,11 +191,8 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
}
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 candidates = plan.files.filter(({ relativePath, bytes }) => isHardlinkableResource(relativePath, bytes));
const total = candidates.reduce((bytes, file) => bytes + file.bytes, 0);
const dataPath = await canonicalCopyPath(record.dataPath);
const linked = new Map((record.hardlinkedFiles ?? []).map((path) => [key(path), path]));
return changeCopyFiles(root, async (incoming) => {
@@ -143,24 +202,24 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
let matches = 0;
let lastReport = 0;
report('checking', 0, total);
for (const { relativePath, evidence } of candidates) {
for (const { relativePath, bytes } 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);
}
const match = await verifyMatchingResource(target, original, bytes, signal);
if (match.status === 'already-linked') {
linked.set(key(relativePath), relativePath);
matches += 1;
} else if (match.status === 'matched') {
const staged = join(incoming, relativePath);
await mkdir(dirname(staged), { recursive: true });
const stagedStamp = await linkVerifiedResource(original, staged, match.sourceStamp);
unchanged.set(target, match.copyStamp);
unchanged.set(staged, stagedStamp);
replacements.push(relativePath);
linked.set(key(relativePath), relativePath);
matches += 1;
}
checked += evidence.bytes;
checked += bytes;
if (checked === total || Date.now() - lastReport >= 250) {
lastReport = Date.now();
report('checking', checked, total);
@@ -175,6 +234,10 @@ export async function compactCopy(record: InstallRecord, root: string, signal: A
}, () => updateCopyRecord(record.id, (latest) => ({ ...latest, hardlinkedFiles: [...linked.values()] })));
}
async function canShareVolume(sourcePath: string, root: string): Promise<boolean> {
return await sameVolume(sourcePath, root) && await sameVolume(sourcePath, dirname(root));
}
async function verifyStagedLinks(
record: InstallRecord, version: string | null, unchanged: ReadonlyMap<string, BigIntStats>, signal: AbortSignal,
): Promise<void> {
@@ -13,7 +13,7 @@ import { gameProcessRunning, launchInProgress } from '../launch/launch-controlle
import { readInstalledLab } from '../launch/lab-handoff.ts';
import { localServerReady } from '../launch/local-server.ts';
import { fileInfo } from './change-copy-files.ts';
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, type Report } from './copy-file-maintenance.ts';
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
let current: { stop: AbortController; interruptible: boolean } | null = null;
@@ -34,6 +34,7 @@ export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
return {
sourceVersion: source?.version ?? null,
updateAvailable: isNewer(source, record.gameVersion),
updatePreservesSpaceSaving: source !== null && await updatePreservesSpaceSaving(record, source, record.copyPath),
spaceSavingAvailable: source !== null && await convertibleCopy(record, source, record.copyPath),
steamConfirmationRequired: steamLibraryNeedsConfirmation(record, copyPath, dataPath),
steamLocations: copyInSteam || dataInSteam ? { copyPath, dataPath, copyInSteam, dataInSteam } : null,
@@ -1,11 +1,11 @@
import { isHardlinkableResource } from '@wto/patcher';
import type { FolderSize } from '@shared/schemas/install.ts';
import { planCopy } from '../install/copy-game.ts';
import { hardlinkResource } from '../install/hardlink-files.ts';
/** Estimate the installation size and the bytes eligible for content verification. */
export async function measureFolder(root: string, version?: string | null): Promise<FolderSize> {
/** Estimate the installation size and the bytes eligible for space-saving hard links. */
export async function measureFolder(root: string): Promise<FolderSize> {
const plan = await planCopy(root);
const linkableBytes = plan.files.reduce((total, file) =>
total + (hardlinkResource(version, file.relativePath, file.bytes)?.bytes ?? 0), 0);
total + (isHardlinkableResource(file.relativePath, file.bytes) ? file.bytes : 0), 0);
return { bytes: plan.totalBytes, files: plan.files.length, linkableBytes };
}
@@ -2,30 +2,11 @@ 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 type ResourceMatchResult =
| { readonly status: 'already-linked'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
| { readonly status: 'matched'; readonly copyStamp: BigIntStats; readonly sourceStamp: BigIntStats }
| { readonly status: 'mismatch' };
export async function fileHash(path: string, signal: AbortSignal): Promise<string> {
const hash = createHash('sha256');
@@ -33,22 +14,56 @@ export async function fileHash(path: string, signal: AbortSignal): Promise<strin
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) => {
export async function statFile(path: string): Promise<BigIntStats | null> {
return 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;
}
/** Capture the file identity of a stock asset right before hardlinking it. */
export async function statHardlinkResource(
path: string,
expectedBytes: number,
signal: AbortSignal,
): Promise<BigIntStats | null> {
signal.throwIfAborted();
const stats = await statFile(path);
if (!stats?.isFile() || stats.size !== BigInt(expectedBytes)) return null;
return stats;
}
/**
* Verify that an existing copy file and stock file have identical contents before replacing the
* copy file with a hard link. Already-linked pairs return immediately without re-hashing.
*/
export async function verifyMatchingResource(
copyPath: string,
sourcePath: string,
expectedBytes: number,
signal: AbortSignal,
): Promise<ResourceMatchResult> {
signal.throwIfAborted();
const [copyBefore, sourceBefore] = await Promise.all([statFile(copyPath), statFile(sourcePath)]);
const size = BigInt(expectedBytes);
if (!copyBefore?.isFile() || !sourceBefore?.isFile() || copyBefore.size !== size || sourceBefore.size !== size) {
return { status: 'mismatch' };
}
if (sameResource(copyBefore, sourceBefore)) {
return { status: 'already-linked', copyStamp: copyBefore, sourceStamp: sourceBefore };
}
const [copyHash, sourceHash] = await Promise.all([fileHash(copyPath, signal), fileHash(sourcePath, signal)]);
const [copyAfter, sourceAfter] = await Promise.all([statFile(copyPath), statFile(sourcePath)]);
if (!copyAfter || !sourceAfter || !sameResource(copyBefore, copyAfter) || !sameResource(sourceBefore, sourceAfter)) {
throw new AppError('hardlink_file_changed');
}
return copyHash === sourceHash
? { status: 'matched', copyStamp: copyAfter, sourceStamp: sourceAfter }
: { status: 'mismatch' };
}
export function sameInode(left: BigIntStats, right: BigIntStats): boolean {
return left.isFile() && right.isFile() && left.dev === right.dev && left.ino === right.ino;
}
export function sameResource(left: BigIntStats, right: BigIntStats): boolean {
File diff suppressed because it is too large. Load diff
@@ -1,7 +1,7 @@
import type { BigIntStats } from 'node:fs';
import { access, mkdir } from 'node:fs/promises';
import { isAbsolute, join, relative } from 'node:path';
import { isInSteamLibrary } from '@wto/patcher';
import { isHardlinkableResource, isInSteamLibrary } from '@wto/patcher';
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';
@@ -9,7 +9,7 @@ import { freeBytes, inspectTargetFolder, sameVolume } from '../game-folder/inspe
import { copyPlannedFiles, planCopy, removeInterruptedCopy, type CopyPlan } from './copy-game.ts';
import { requireUnredirectedData } from './data-location.ts';
import { discardDecalCache, importDecalCache } from './decals.ts';
import { hardlinkResource, hasHardlinkEvidence, verifyHardlinkResource } from './hardlink-files.ts';
import { statHardlinkResource } from './hardlink-files.ts';
import { canonicalCopyPath, copyPathContains, requireAvailableCopy, writeInstallRecord } from './install-record.ts';
import { checkPatches } from './patch-check.ts';
import { backUpStockFiles, installStockSource, refreshStockBackup, refreshStockBackupFrom, requireStockBackupLocation, stockBackupPath } from './stock-backup.ts';
@@ -90,7 +90,7 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
}
try {
const copied = request.method === 'copy'
? await copyGame(sourcePath, copyPath, target!.freeBytes, useHardLinks ? version : null, signal, report)
? await copyGame(sourcePath, copyPath, target!.freeBytes, useHardLinks, version, signal, report)
: undefined;
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
@@ -150,7 +150,7 @@ async function inspectInstallation(request: InstallRequest) {
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, sourcePath) : null;
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
const useHardLinks = request.method === 'copy' && request.useHardLinks === true;
if (useHardLinks && (!target?.sameDriveAsStock || !hasHardlinkEvidence(game.version))) {
if (useHardLinks && !target?.sameDriveAsStock) {
throw new AppError('hardlink_unavailable');
}
const copyInSteam = isInSteamLibrary(requestedCopyPath) || isInSteamLibrary(copyPath);
@@ -178,16 +178,17 @@ async function copyGame(
source: string,
target: string,
initialFreeBytes: number | null,
hardlinkVersion: string | null,
useHardLinks: boolean,
sourceVersion: string | null,
signal: AbortSignal,
report: (progress: InstallProgress) => void,
): Promise<Pick<InstallRecord, 'sourceFiles' | 'hardlinkedFiles'>> {
report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const plan = await planCopy(source);
const hardlinks = hardlinkVersion ? await confirmHardlinks(source, hardlinkVersion, plan, signal, report) : undefined;
const hardlinks = useHardLinks ? await prepareHardlinks(source, 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)) {
if (hardlinks && (!await sameVolume(source, target) || (await inspectGameFolder(source)).version !== sourceVersion)) {
throw new AppError('hardlink_file_changed');
}
const available = hardlinks ? await freeBytes(target) : initialFreeBytes;
@@ -200,7 +201,7 @@ async function copyGame(
try {
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');
if (hardlinks && (await inspectGameFolder(source)).version !== sourceVersion) throw new AppError('hardlink_file_changed');
return {
sourceFiles: plan.files.map((file) => file.relativePath),
...(hardlinks ? { hardlinkedFiles: [...hardlinks.keys()] } : {}),
@@ -214,26 +215,22 @@ async function copyGame(
}
}
async function confirmHardlinks(
async function prepareHardlinks(
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 candidates = plan.files.filter((file) => isHardlinkableResource(file.relativePath, file.bytes));
const totalBytes = candidates.reduce((total, file) => total + file.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;
for (const file of candidates) {
const verified = await statHardlinkResource(join(source, file.relativePath), file.bytes, signal);
if (verified) links.set(file.relativePath, verified);
doneBytes += file.bytes;
doneFiles += 1;
report({ phase: 'verifying', doneBytes, totalBytes, doneFiles, totalFiles: candidates.length });
}