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:
1 parent
3ed41bdd60
commit
bf2ce539e7
14 files changed
+292
-2812
No files matched your search
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -157,9 +157,9 @@
|
||||
"copy": "Copy installation (recommended)",
|
||||
"copyBody": "Copies the game to a new folder. Requires about {{size}} of free space.",
|
||||
"spaceSaving": "Space-saving copy",
|
||||
"spaceSavingBody": "Shares verified large resources on the same volume. Estimated space required is {{size}}. A Steam update in place can change shared files in the client.",
|
||||
"spaceSavingBody": "Shares read-only resource archives on the same volume. Estimated space required is {{size}}. An in-place update to the source client can change shared files in this client.",
|
||||
"spaceSavingPending": "Calculating how much space can be saved.",
|
||||
"spaceSavingUnavailable": "This installation has no large resources eligible for space-saving copying.",
|
||||
"spaceSavingUnavailable": "This installation has no read-only resource archives eligible for space-saving copying.",
|
||||
"sameVolumeRequired": "Select a destination on the same volume as the original installation.",
|
||||
"targetTitle": "Select an install location (a WTOffline subfolder will be created)",
|
||||
"targetSubfolderHint": "A dedicated WTOffline folder is automatically created under the selected location to keep game files organized.",
|
||||
@@ -232,12 +232,13 @@
|
||||
"update": "Update from online installation",
|
||||
"updateAction": "Update client",
|
||||
"newVersion": "Version {{version}} is available from the installation source.",
|
||||
"updateDetaches": "Version {{version}} is available. Updating copies shared resources into independent files and requires additional space.",
|
||||
"updateKeepsSpaceSaving": "Version {{version}} is available. Updating continues sharing read-only resource archives with the source.",
|
||||
"updateDetaches": "Version {{version}} is available. Because the client and source are on different volumes, updating copies shared resources into independent files and requires additional space.",
|
||||
"currentVersion": "Installation source version {{version}}",
|
||||
"noSource": "Installation source unavailable",
|
||||
"spaceSaving": "Save space",
|
||||
"spaceSavingHint": "Share identical verified resources with the source. A Steam update in place can change the shared files.",
|
||||
"spaceSavingUnavailable": "Requires a client and source installation of the same checked version on the same volume.",
|
||||
"spaceSavingHint": "Share identical read-only resource archives with the source. An in-place update to the source client can change the shared files.",
|
||||
"spaceSavingUnavailable": "Requires a client and source installation of the same version on the same volume.",
|
||||
"compactAction": "Convert",
|
||||
"check": "Recheck patches",
|
||||
"checkHint": "Check the original file backup.",
|
||||
@@ -726,8 +727,8 @@
|
||||
"missing_features_not_accepted": "Some patches do not apply. Confirm whether to continue without the affected features.",
|
||||
"patch_check_failed": "An error occurred while checking patches.",
|
||||
"copy_failed": "Copying the game files failed. The copied files have been deleted.",
|
||||
"hardlink_unavailable": "Space-saving copying requires a verified game version and a destination on the same volume.",
|
||||
"hardlink_no_match": "The files do not match the verified resources for space-saving copying.",
|
||||
"hardlink_unavailable": "Space-saving copying requires the destination and source to be on the same volume, and converting an existing client also requires matching versions.",
|
||||
"hardlink_no_match": "No matching read-only resource archives were found, or their contents differ from the source.",
|
||||
"hardlink_file_changed": "A resource changed during verification or copying. Finish any other file operation, then retry.",
|
||||
"install_cancelled": "Installation cancelled. The copied files have been deleted.",
|
||||
"install_busy": "An installation is already in progress.",
|
||||
|
||||
@@ -157,9 +157,9 @@
|
||||
"copy": "复制安装(推荐)",
|
||||
"copyBody": "将游戏复制到新文件夹。需要约 {{size}} 的可用空间。",
|
||||
"spaceSaving": "节省空间的复制",
|
||||
"spaceSavingBody": "与同一磁盘卷上的原版共用已核对的大资源,预计需要 {{size}}。Steam 就地更新可能改变客户端中的共享文件。",
|
||||
"spaceSavingBody": "与同一磁盘卷上的原版共用只读资源包,预计需要 {{size}}。原版就地更新可能改变客户端中的共享文件。",
|
||||
"spaceSavingPending": "正在估算可节省的空间。",
|
||||
"spaceSavingUnavailable": "该安装目录没有可用于省空间复制的大型资源。",
|
||||
"spaceSavingUnavailable": "该安装目录没有可用于省空间复制的只读资源包。",
|
||||
"sameVolumeRequired": "请选择与原版位于同一磁盘卷的目标文件夹。",
|
||||
"targetTitle": "选择安装位置(将自动创建 WTOffline 子文件夹)",
|
||||
"targetSubfolderHint": "将在所选位置下自动创建独立的 WTOffline 文件夹存放游戏文件,避免文件散落。",
|
||||
@@ -232,12 +232,13 @@
|
||||
"update": "从在线版更新",
|
||||
"updateAction": "更新客户端",
|
||||
"newVersion": "安装来源已更新至 {{version}}。",
|
||||
"updateDetaches": "安装来源中有新版本 {{version}}。更新会把共享资源复制为独立文件,需要额外空间。",
|
||||
"updateKeepsSpaceSaving": "安装来源中有新版本 {{version}}。更新时会继续与原版共用只读资源包。",
|
||||
"updateDetaches": "安装来源中有新版本 {{version}}。当前与安装来源不在同一磁盘卷,更新会把共享资源复制为独立文件,需要额外空间。",
|
||||
"currentVersion": "安装来源版本 {{version}}",
|
||||
"noSource": "安装来源不可用",
|
||||
"spaceSaving": "节省空间",
|
||||
"spaceSavingHint": "将内容一致且已核对的资源与原版共用。Steam 就地更新可能改变这些文件。",
|
||||
"spaceSavingUnavailable": "客户端和安装来源须位于同一磁盘卷,并且使用相同的已核对版本。",
|
||||
"spaceSavingHint": "将内容一致的只读资源包与原版共用。原版就地更新可能改变这些文件。",
|
||||
"spaceSavingUnavailable": "客户端和安装来源须位于同一磁盘卷,并且版本一致。",
|
||||
"compactAction": "转换",
|
||||
"check": "重新检查补丁",
|
||||
"checkHint": "核对原版文件备份。",
|
||||
@@ -726,8 +727,8 @@
|
||||
"missing_features_not_accepted": "部分补丁不适用,请先确认是否在缺少相应功能的情况下继续。",
|
||||
"patch_check_failed": "检查补丁时出错。",
|
||||
"copy_failed": "复制游戏文件失败,已复制的文件已删除。",
|
||||
"hardlink_unavailable": "省空间复制需要已核对的游戏版本,并且目标与原版位于同一磁盘卷。",
|
||||
"hardlink_no_match": "文件内容与可共用的实测资源不一致。",
|
||||
"hardlink_unavailable": "省空间复制要求目标与原版位于同一磁盘卷,转换已有客户端还要求版本一致。",
|
||||
"hardlink_no_match": "未找到可共用的只读资源包,或文件内容与原版不一致。",
|
||||
"hardlink_file_changed": "核对或复制过程中有资源文件发生变化。请等待其他文件操作完成后重试。",
|
||||
"install_cancelled": "安装已取消,已复制的文件已删除。",
|
||||
"install_busy": "已有安装正在进行。",
|
||||
|
||||
@@ -32,7 +32,9 @@ export function CopyMaintenanceActions({ record, info, busy, onRun, onConfirmSte
|
||||
)}
|
||||
<Row label={t('copies.maintenance.update')} hint={info?.sourceVersion
|
||||
? t(info.updateAvailable
|
||||
? (record.hardlinkedFiles?.length ? 'copies.maintenance.updateDetaches' : 'copies.maintenance.newVersion')
|
||||
? (record.hardlinkedFiles?.length
|
||||
? (info.updatePreservesSpaceSaving ? 'copies.maintenance.updateKeepsSpaceSaving' : 'copies.maintenance.updateDetaches')
|
||||
: 'copies.maintenance.newVersion')
|
||||
: 'copies.maintenance.currentVersion', { version: info.sourceVersion })
|
||||
: t('copies.maintenance.noSource')}>
|
||||
<button type="button" className={info?.updateAvailable ? 'button button-primary' : 'button'}
|
||||
|
||||
@@ -14,6 +14,7 @@ export const MaintenanceRequestSchema = z.object({
|
||||
export const MaintenanceInfoSchema = z.object({
|
||||
sourceVersion: z.string().nullable(),
|
||||
updateAvailable: z.boolean(),
|
||||
updatePreservesSpaceSaving: z.boolean(),
|
||||
spaceSavingAvailable: z.boolean(),
|
||||
steamConfirmationRequired: z.boolean(),
|
||||
steamLocations: z.object({
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/** Version-independent read-only asset rules for space-saving hardlink copies. */
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { parseJsonc } from '@wto/jsonc';
|
||||
import { GAME_FILES } from './game-copy.ts';
|
||||
|
||||
export interface HardlinkResourceRules {
|
||||
readonly allowedDirectories: readonly string[];
|
||||
readonly allowedExtensions: readonly string[];
|
||||
readonly minBytes: number;
|
||||
}
|
||||
|
||||
const TUNING_FILE = new URL('../tuning/hardlink-resources.jsonc', import.meta.url);
|
||||
const PROTECTED_FILES = new Set(Object.values(GAME_FILES).map((path) => path.replaceAll('\\', '/').toLowerCase()));
|
||||
|
||||
let cached: HardlinkResourceRules | null = null;
|
||||
|
||||
export function hardlinkResourceRules(): HardlinkResourceRules {
|
||||
if (cached) return cached;
|
||||
const value = parseJsonc(readFileSync(TUNING_FILE, 'utf8'));
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||
throw tuningError('the file is not an object');
|
||||
}
|
||||
const fields = value as Record<string, unknown>;
|
||||
const allowedDirectories = readDirectories(fields, 'allowed_directories');
|
||||
const allowedExtensions = readExtensions(fields, 'allowed_extensions');
|
||||
const minBytes = readNonNegativeInteger(fields, 'min_bytes');
|
||||
cached = { allowedDirectories, allowedExtensions, minBytes };
|
||||
return cached;
|
||||
}
|
||||
|
||||
/** Whether a relative path inside a stock client is a static read-only asset safe to hardlink. */
|
||||
export function isHardlinkableResource(relativePath: string, bytes: number): boolean {
|
||||
const rules = hardlinkResourceRules();
|
||||
if (!Number.isFinite(bytes) || bytes < 0 || bytes < rules.minBytes) return false;
|
||||
const normalized = relativePath.replaceAll('\\', '/').toLowerCase();
|
||||
if (!normalized || normalized.startsWith('/') || normalized.includes('../') || normalized === '..') return false;
|
||||
if (normalized.startsWith('wtoffline/') || PROTECTED_FILES.has(normalized)) return false;
|
||||
return rules.allowedDirectories.some((dir) => normalized.startsWith(dir)) &&
|
||||
rules.allowedExtensions.some((ext) => normalized.endsWith(ext));
|
||||
}
|
||||
|
||||
function readDirectories(fields: Record<string, unknown>, key: string): readonly string[] {
|
||||
const raw = fields[key];
|
||||
if (!Array.isArray(raw) || raw.length === 0) throw tuningError(`"${key}" must be a non-empty string array`);
|
||||
return raw.map((item) => {
|
||||
if (typeof item !== 'string' || !item.endsWith('/') || item.startsWith('/') || item.includes('\\') || item.includes('..')) {
|
||||
throw tuningError(`"${key}" entries must be lowercase relative prefixes ending with "/"`);
|
||||
}
|
||||
return item.toLowerCase();
|
||||
});
|
||||
}
|
||||
|
||||
function readExtensions(fields: Record<string, unknown>, key: string): readonly string[] {
|
||||
const raw = fields[key];
|
||||
if (!Array.isArray(raw) || raw.length === 0) throw tuningError(`"${key}" must be a non-empty string array`);
|
||||
return raw.map((item) => {
|
||||
if (typeof item !== 'string' || !item.startsWith('.') || item.length < 2 || item.includes('/') || item.includes('\\')) {
|
||||
throw tuningError(`"${key}" entries must be file extensions starting with "."`);
|
||||
}
|
||||
return item.toLowerCase();
|
||||
});
|
||||
}
|
||||
|
||||
function readNonNegativeInteger(fields: Record<string, unknown>, key: string): number {
|
||||
const value = fields[key];
|
||||
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
|
||||
throw tuningError(`"${key}" must be a non-negative integer`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function tuningError(detail: string): Error {
|
||||
return new Error(`tuning/hardlink-resources.jsonc: ${detail}`);
|
||||
}
|
||||
@@ -18,6 +18,11 @@ export { blockingFailures, ESSENTIAL_FEATURES } from './essential-features.ts';
|
||||
export { patchExecutable, type ExecutableResult } from './executable.ts';
|
||||
export { assertWritableCopy, GAME_FILES, isInSteamLibrary, type WritableCopyOptions } from './game-copy.ts';
|
||||
export { executableVersion } from './game-version.ts';
|
||||
export {
|
||||
hardlinkResourceRules,
|
||||
isHardlinkableResource,
|
||||
type HardlinkResourceRules,
|
||||
} from './hardlink-resources.ts';
|
||||
export { rebuildGuiPack, type AppliedGuiPatch, type GuiPackResult } from './gui-pack.ts';
|
||||
export { loadGuiPatches, type GuiScriptEdit, type GuiScriptPatch, type GuiScriptVariant } from './gui-patch-definition.ts';
|
||||
export { ENGINE_SETTINGS_PATH, EXTRA_STORE_BUNDLE_GUID_MAP, EXTRA_STORE_BUNDLE_GUIDS, rebuildMainPack, type MainPackResult } from './main-pack.ts';
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// Rules for space-saving NTFS hardlink copies between the stock client and an offline client.
|
||||
// Matching is version-independent so minor updates keep working without regenerating per-version
|
||||
// hash lists. Only static read-only engine asset archives that the game process never writes to
|
||||
// belong here; executables, vromfs archives, configs, metadata, and hotfix overlays stay copied.
|
||||
{
|
||||
// Relative directory prefixes (lowercase, trailing slash) containing read-only asset packs.
|
||||
"allowed_directories": [
|
||||
"content/",
|
||||
"content.hq/"
|
||||
],
|
||||
|
||||
// Lowercase file suffixes for static texture and model archives.
|
||||
"allowed_extensions": [
|
||||
".dxp.bin",
|
||||
".grp"
|
||||
],
|
||||
|
||||
// Minimum file size in bytes (0 links every matching archive regardless of size).
|
||||
"min_bytes": 0
|
||||
}
|
||||
Reference in new issue
Block a user