feat(launcher): add maintenance for installed game copies

This commit is contained in:
N0VAN0M4LY committed 2026-11-29 15:24:21 +08:00
1 parent 7d68dc0548
commit ef3648cb13
17 files changed
+672 -24

No files matched your search

@@ -0,0 +1,76 @@
import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises';
import { dirname, isAbsolute, join, normalize, relative, sep } from 'node:path';
import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts';
export async function fileInfo(path: string) {
try {
return await lstat(path);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
return null;
}
}
export async function stagedPath(root: string, name: string): Promise<string> {
const part = normalize(name);
if (!part || part === '.' || isAbsolute(part) || part === '..' || part.startsWith('..' + sep)) {
throw new Error('Invalid path in the copy inventory: ' + name);
}
const path = join(root, part);
if (!copyPathContains(root, await canonicalCopyPath(dirname(path)))) {
throw new Error('A directory points outside the copy: ' + path);
}
return path;
}
export async function changeCopyFiles<T>(
root: string,
prepare: (folder: string) => Promise<{ replace: readonly string[]; remove: readonly string[] }>,
recordChange: () => Promise<T>,
): Promise<T> {
const work = await mkdtemp(join(dirname(root), '.wto-copy-'));
const incoming = join(work, 'new');
const backups = join(work, 'old');
const changes: Array<{ target: string; saved: string | null; replaced: boolean }> = [];
let keepBackups = false;
try {
const { replace, remove } = await prepare(incoming);
for (const [paths, add] of [[replace, true], [remove, false]] as const) {
for (const path of paths) {
const target = await stagedPath(root, path);
const old = await fileInfo(target);
if (old?.isDirectory()) throw new Error('A game file is a directory: ' + target);
if (!old && !add) continue;
const entry = { target, saved: null as string | null, replaced: false };
if (old) {
const saved = join(backups, path);
await mkdir(dirname(saved), { recursive: true });
await rename(target, saved);
entry.saved = saved;
}
changes.push(entry);
if (add) {
await mkdir(dirname(target), { recursive: true });
await rename(join(incoming, path), target);
entry.replaced = true;
}
}
}
return await recordChange();
} catch (error) {
for (const { target, saved, replaced } of changes.reverse()) {
try {
if (replaced) await rm(target, { force: true });
if (saved) await rename(saved, target);
} catch (rollbackError) {
keepBackups = true;
console.error('[copies] could not restore a file, recovery folder:', work, target, rollbackError);
}
}
throw error;
} finally {
if (!keepBackups && relative(dirname(root), dirname(work)) === '') {
await rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error));
}
}
}
@@ -0,0 +1,267 @@
import { createHash } from 'node:crypto';
import { createReadStream } from 'node:fs';
import { copyFile, 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';
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 { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.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';
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
import { labStatusUrl, readInstalledLab } from '../launch/lab-handoff.ts';
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
let current: { stop: AbortController; interruptible: boolean } | null = null;
export function maintenanceInProgress(): boolean {
return current !== null;
}
export function cancelMaintenance(): void {
if (current?.interruptible) current.stop.abort();
}
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) };
}
export async function maintainCopy(
request: MaintenanceRequest,
publish: (progress: MaintenanceProgress) => void,
): Promise<Copies> {
if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
const job = { stop: new AbortController(), interruptible: request.operation === 'update' };
current = job;
const signal = job.stop.signal;
const report = (phase: MaintenanceProgress['phase'], doneBytes = 0, totalBytes = 0): void => {
if (phase === 'applying') job.interruptible = false;
publish({ id: request.id, operation: request.operation, phase, doneBytes, totalBytes });
};
report('checking');
try {
const record = await requireCopy(request.id);
const root = await checkedRoot(record);
if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy');
signal.throwIfAborted();
switch (request.operation) {
case 'check':
return await recordCheck(record, record.stockBackupPath);
case 'repair':
return await repair(record, root, () => report('applying'));
case 'update':
return await updateFromSource(record, root, signal, report);
case 'delete':
report('applying');
return await remove(record, root, request.deleteData);
}
} catch (error) {
if (signal.aborted) throw new AppError('maintenance_cancelled');
if (error instanceof AppError) throw error;
console.error('[copies] maintenance failed:', request.operation, error);
throw new AppError('maintenance_failed');
} finally {
current = null;
}
}
async function requireCopy(id: string): Promise<InstallRecord> {
const record = (await listCopies()).copies.find((copy) => copy.id === id);
if (!record) throw new AppError('copy_not_found');
return record;
}
async function readSource(record: InstallRecord): Promise<GameFolderInspection | null> {
if (!record.sourcePath) return null;
try {
const game = await inspectGameFolder(record.sourcePath);
return game.missingFiles.length > 0 ? null : game;
} catch (error) {
if (error instanceof AppError) return null;
throw error;
}
}
function isNewer(source: GameFolderInspection | null, version: string | null): boolean {
return !!source?.version && !!version && compareVersions(source.version, version) > 0;
}
async function checkedRoot(record: InstallRecord): Promise<string> {
const root = await safeFolder(record.copyPath);
const backup = await canonicalCopyPath(record.stockBackupPath);
if (relative(join(root, STOCK_BACKUP_FOLDER), backup) !== '') throw new AppError('maintenance_location');
if (record.sourcePath) {
const source = await canonicalCopyPath(record.sourcePath);
if (copyPathContains(source, root) || copyPathContains(root, source)) throw new AppError('maintenance_location');
}
return root;
}
async function safeFolder(path: string): Promise<string> {
const root = await canonicalCopyPath(path);
if (!isAbsolute(path) || root === parse(root).root || isInSteamLibrary(root) ||
copyPathContains(root, await canonicalCopyPath(app.getAppPath())) ||
copyPathContains(root, await canonicalCopyPath(app.getPath('userData')))) {
throw new AppError('maintenance_location');
}
if ((await fileInfo(path))?.isSymbolicLink()) throw new AppError('maintenance_location');
return root;
}
async function labServerUses(root: string): Promise<boolean> {
const lab = await readInstalledLab().catch(() => null);
if (!lab || relative(lab.copyPath, root) !== '') return false;
try {
const response = await fetch(labStatusUrl(lab.port), { signal: AbortSignal.timeout(800) });
return response.ok && (await response.json() as { app?: string }).app === 'wto-server';
} catch {
return false;
}
}
async function recordCheck(record: InstallRecord, folder: string): Promise<Copies> {
const check = await checkPatches(folder, record.dataPath);
return updateCopyRecord(record.id, (copy) => ({
...copy, unavailablePatches: check.unavailable, lastCheckedAt: new Date().toISOString(),
}));
}
async function repair(record: InstallRecord, root: string, applying: () => void): Promise<Copies> {
return changeCopyFiles(root, async (incoming) => {
const files = Object.values(GAME_FILES);
for (const file of files) await stageBackup(record.stockBackupPath, file, join(incoming, file));
applying();
return { replace: files, remove: [] };
}, listCopies);
}
type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void;
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');
const dataPath = await canonicalCopyPath(record.dataPath);
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 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) {
changed.push(file);
} else if (Math.trunc(old.mtimeMs) !== Math.trunc(file.modifiedAt)) {
const [targetHash, sourceHash] = await Promise.all([
fileHash(target, signal), fileHash(join(game.path, file.relativePath), signal),
]);
if (targetHash !== sourceHash) changed.push(file);
}
}
for (const file of remove) await scopedInstallFile(dataPath, root, file);
signal.throwIfAborted();
const check = await checkPatches(game.path, record.dataPath);
signal.throwIfAborted();
const copy: CopyPlan = {
files: changed,
folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))],
totalBytes: changed.reduce((total, file) => total + file.bytes, 0),
};
return changeCopyFiles(root, async (incoming) => {
report('copying', 0, copy.totalBytes);
let lastReport = 0;
await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => {
if (doneBytes === copy.totalBytes || Date.now() - lastReport >= 250) {
lastReport = Date.now();
report('copying', doneBytes, copy.totalBytes);
}
});
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));
}
for (const file of plan.files) {
signal.throwIfAborted();
const info = await fileInfo(join(game.path, file.relativePath));
if (!info?.isFile() || info.size !== file.bytes || info.mtimeMs !== file.modifiedAt) {
throw new AppError('maintenance_source_changed');
}
}
signal.throwIfAborted();
report('applying', copy.totalBytes, copy.totalBytes);
return { replace: [...changed.map(({ relativePath }) => relativePath), ...stockFiles], remove };
}, () => updateCopyRecord(record.id, (latest) => ({
...latest, gameVersion: game.version, unavailablePatches: check.unavailable,
lastCheckedAt: new Date().toISOString(), sourceFiles: inventory,
})));
}
function key(path: string): string {
const name = normalize(path);
return process.platform === 'win32' ? name.toLowerCase() : name;
}
async function scopedInstallFile(dataPath: string, root: string, name: string): Promise<string> {
const target = await stagedPath(root, name);
if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target) ||
copyPathContains(dataPath, target)) {
throw new AppError('maintenance_location');
}
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 stageBackup(folder: string, file: string, target: string): Promise<void> {
await mkdir(dirname(target), { recursive: true });
const source = join(folder, file);
if (!(await fileInfo(source))?.isFile()) throw new AppError('maintenance_location');
await copyFile(source, target);
}
async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise<Copies> {
const data = deleteData ? await safeFolder(record.dataPath) : await canonicalCopyPath(record.dataPath);
const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null;
if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) ||
(relative(data, root) !== '' && copyPathContains(data, root)))) {
throw new AppError('maintenance_location');
}
if (!deleteData && copyPathContains(root, data)) {
await removeExcept(root, data);
} else {
await rm(root, { recursive: true, force: true });
}
if (deleteData && !copyPathContains(root, data)) await rm(data, { recursive: true, force: true });
return removeCopyRecord(record.id);
}
/** Keep the data folder in place when it was chosen inside this copy. */
async function removeExcept(folder: string, kept: string): Promise<void> {
if (relative(folder, kept) === '' || !(await fileInfo(folder))) return;
for (const entry of await readdir(folder, { withFileTypes: true })) {
const path = join(folder, entry.name);
if (copyPathContains(path, kept)) {
if (!entry.isDirectory()) throw new AppError('maintenance_location');
await removeExcept(path, kept);
} else {
await rm(path, { recursive: true, force: true });
}
}
}
@@ -1,5 +1,5 @@
import { createReadStream, createWriteStream } from 'node:fs';
import { lstat, mkdir, readdir, rm } from 'node:fs/promises';
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';
@@ -20,6 +20,7 @@ const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screensh
interface CopyEntry {
readonly relativePath: string;
readonly bytes: number;
readonly modifiedAt: number;
}
export interface CopyPlan {
@@ -48,9 +49,9 @@ export async function planCopy(source: string): Promise<CopyPlan> {
folders.push(relative(source, path));
pending.push(path);
} else if (entry.isFile()) {
const bytes = (await lstat(path)).size;
files.push({ relativePath: relative(source, path), bytes });
totalBytes += bytes;
const { size, mtimeMs } = await lstat(path);
files.push({ relativePath: relative(source, path), bytes: size, modifiedAt: mtimeMs });
totalBytes += size;
}
}
}
@@ -100,6 +101,8 @@ export async function copyPlannedFiles(
createWriteStream(join(target, file.relativePath), { flags: 'wx' }),
{ signal: stopSignal },
);
const modified = new Date(file.modifiedAt);
await utimes(join(target, file.relativePath), modified, modified);
doneFiles += 1;
onProgress({ doneBytes, doneFiles });
}
@@ -25,6 +25,10 @@ const PROGRESS_INTERVAL_MS = 250;
let running: AbortController | null = null;
export function installationInProgress(): boolean {
return running !== null;
}
export async function installGame(request: InstallRequest, onProgress: (progress: InstallProgress) => void): Promise<InstallRecord> {
if (running) throw new AppError('install_busy');
const controller = new AbortController();
@@ -82,7 +86,9 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
if (check.unavailable.length && !request.missingFeaturesAccepted) throw new AppError('missing_features_not_accepted');
signal.throwIfAborted();
if (request.method === 'copy') await copyGame(request.sourcePath, copyPath, target!.freeBytes, signal, report);
const sourceFiles = request.method === 'copy'
? await copyGame(request.sourcePath, copyPath, target!.freeBytes, signal, report)
: undefined;
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const stockBackup = await backUpStockFiles(copyPath);
@@ -99,6 +105,8 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr
gameVersion: game.version,
unavailablePatches: check.unavailable,
installedAt: new Date().toISOString(),
lastCheckedAt: new Date().toISOString(),
...(sourceFiles ? { sourceFiles } : {}),
};
await writeInstallRecord(record);
return record;
@@ -110,7 +118,7 @@ async function copyGame(
freeBytes: number | null,
signal: AbortSignal,
report: (progress: InstallProgress) => void,
): Promise<void> {
): Promise<string[]> {
report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const plan = await planCopy(source);
if (freeBytes !== null && freeBytes < plan.totalBytes + SPARE_BYTES) {
@@ -121,6 +129,7 @@ async function copyGame(
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);
} 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');
@@ -56,13 +56,24 @@ export function setCurrentCopy(id: string): Promise<Copies> {
});
}
export function renameCopy(id: string, name: string): Promise<Copies> {
export function updateCopyRecord(id: string, change: (record: InstallRecord) => InstallRecord): Promise<Copies> {
return changeRegistry((registry) => {
if (!registry.copies.some((copy) => copy.id === id)) throw new AppError('copy_not_found');
return { ...registry, copies: registry.copies.map((copy) => copy.id === id ? { ...copy, name } : copy) };
if (!registry.copies.some((record) => record.id === id)) throw new AppError('copy_not_found');
return { ...registry, copies: registry.copies.map((record) => record.id === id ? change(record) : record) };
});
}
export function removeCopyRecord(id: string): Promise<Copies> {
return changeRegistry((registry) => {
const copies = registry.copies.filter((record) => record.id !== id);
return { ...registry, copies, current: registry.current === id ? copies[0]?.id ?? null : registry.current };
});
}
export function renameCopy(id: string, name: string): Promise<Copies> {
return updateCopyRecord(id, (record) => ({ ...record, name }));
}
/** Serialize writes so switching, renaming and completing an installation preserve each other. */
function changeRegistry(change: (registry: Copies) => Promise<Copies> | Copies): Promise<Copies> {
const operation = pending.then(async () => {
@@ -81,30 +92,31 @@ function changeRegistry(change: (registry: Copies) => Promise<Copies> | Copies):
}
async function requireUniquePaths(registry: Copies, id: string, copyPath: string, dataPath: string): Promise<void> {
const paths = await Promise.all([canonical(copyPath), canonical(dataPath)]);
const paths = await Promise.all([canonicalCopyPath(copyPath), canonicalCopyPath(dataPath)]);
for (const existing of registry.copies) {
const used = await Promise.all([canonical(existing.copyPath), canonical(existing.dataPath)]);
const used = await Promise.all([canonicalCopyPath(existing.copyPath), canonicalCopyPath(existing.dataPath)]);
if (id === existing.id || paths.some((path) => used.some((other) => overlaps(path, other)))) {
throw new AppError('copy_location_in_use');
}
}
}
export function copyPathContains(parent: string, child: string): boolean {
const remainder = relative(parent, child);
return !isAbsolute(remainder) && remainder !== '..' && !remainder.startsWith('..' + sep);
}
function overlaps(left: string, right: string): boolean {
function contains(parent: string, child: string): boolean {
const remainder = relative(parent, child);
return !isAbsolute(remainder) && remainder !== '..' && !remainder.startsWith('..' + sep);
}
return contains(left, right) || contains(right, left);
return copyPathContains(left, right) || copyPathContains(right, left);
}
/** Resolve junctions in a path even when its final folders have yet to be made. */
async function canonical(path: string): Promise<string> {
export async function canonicalCopyPath(path: string): Promise<string> {
const absolute = resolve(path);
try {
return await realpath(absolute);
} catch {
const parent = dirname(absolute);
return parent === absolute ? absolute : join(await canonical(parent), relative(parent, absolute));
return parent === absolute ? absolute : join(await canonicalCopyPath(parent), relative(parent, absolute));
}
}
@@ -25,6 +25,16 @@ interface LaunchJob {
let active: LaunchJob | null = null;
let state: LaunchState = { phase: 'ready' };
export function launchInProgress(): boolean {
return active !== null;
}
export async function gameProcessRunning(signal: AbortSignal): Promise<boolean> {
if (process.platform !== 'win32') return false;
const games = await execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal });
return /^"aces\.exe",/im.test(games.stdout);
}
export function getLaunchState(): LaunchState {
return state;
}
@@ -107,11 +117,11 @@ async function launch(job: LaunchJob): Promise<void> {
const [labVersion, stockVersion, games] = await Promise.all([
readVersion(lab.copyPath, signal),
readVersion(stockPath, signal),
execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal }),
gameProcessRunning(signal),
]);
signal.throwIfAborted();
if (!labVersion || labVersion !== stockVersion) throw new AppError('launch_lab_version');
if (/^"aces\.exe",/im.test(games.stdout)) throw new AppError('launch_game_running');
if (games) throw new AppError('launch_game_running');
await checkPort(lab.port);
signal.throwIfAborted();
update(job, { phase: 'building', port: lab.port });