Files
WT-Offline/apps/launcher/src/main/services/copies/copy-maintenance.ts
T
N0VAN0M4LY 49264b0326 feat(launcher): add client origin marker and stock restore removal flow
Write a self-describing wtoffline/client.json origin marker (copy, hardlink, or in-place) on install, space-saving compaction, and hardlink-detaching updates, and read it with lightweight hardlink nlink sampling when inspecting existing folders. Allow deleting existing folders only when backed by a valid copy/hardlink marker outside Steam and disjoint from all registered source paths, and add an atomic restore-stock-and-remove option that restores the four stock core files and removes only wto_ws.{dll,cfg,log} and wtoffline/.
2026-12-04 20:38:08 +08:00

186 lines
7.3 KiB
TypeScript

import { isAbsolute, relative } from 'node:path';
import { isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { Copies, InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
import { detectHardlinkedResources, readClientMarker } from '../install/client-marker.ts';
import { installationInProgress } from '../install/install-game.ts';
import { canonicalCopyPath, listCopies, steamLibraryNeedsConfirmation, updateCopyRecord } from '../install/install-record.ts';
import { checkPatches } from '../install/patch-check.ts';
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
import { readInstalledLab } from '../launch/lab-handoff.ts';
import { localServerReady } from '../launch/local-server.ts';
import { compactCopy, convertibleCopy, isNewer, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
import {
canDeleteCopyFiles,
canRestoreStock,
checkedRoot,
failLocation,
removeCopy,
resolveClientOrigin,
withCanonicalSources,
} from './copy-removal.ts';
import { readSource, setCopySource } from './copy-source.ts';
export { canDeleteCopyFiles, canRestoreStock, resolveClientOrigin } from './copy-removal.ts';
let current: {
stop: AbortController;
interruptible: boolean;
progress: MaintenanceProgress;
} | null = null;
export function maintenanceInProgress(): boolean {
return current !== null;
}
export function maintenanceState(): MaintenanceProgress | null {
return current ? { ...current.progress } : null;
}
export function cancelMaintenance(): void {
if (current?.interruptible) current.stop.abort();
}
export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
const registry = await listCopies();
const record = registry.copies.find((copy) => copy.id === id);
if (!record) throw new AppError('copy_not_found');
const [source, copyPath, dataPath, canonicalCopies] = await Promise.all([
readSource(record),
canonicalCopyPath(record.copyPath),
canonicalCopyPath(record.dataPath),
withCanonicalSources(registry.copies),
]);
const [diskMarker, hasHardlinkedResources, canRestoreAndRemove] = await Promise.all([
readClientMarker(copyPath),
detectHardlinkedResources(copyPath),
canRestoreStock(record, copyPath),
]);
const clientOrigin = resolveClientOrigin(record, diskMarker);
const canDeleteFiles = canDeleteCopyFiles(record, copyPath, clientOrigin, registry.copies) &&
canDeleteCopyFiles(record, copyPath, clientOrigin, canonicalCopies);
const copyInSteam = isInSteamLibrary(record.copyPath) || isInSteamLibrary(copyPath);
const dataInSteam = isInSteamLibrary(record.dataPath) || isInSteamLibrary(dataPath);
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,
clientOrigin,
hasHardlinkedResources,
canDeleteFiles,
canRestoreAndRemove,
};
}
export async function maintainCopy(
request: MaintenanceRequest,
publish: (progress: MaintenanceProgress | null) => void,
): Promise<Copies> {
if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
const initial: MaintenanceProgress = {
id: request.id,
operation: request.operation,
phase: 'checking',
doneBytes: 0,
totalBytes: 0,
};
const job = {
stop: new AbortController(),
interruptible: request.operation === 'update' || request.operation === 'compact',
progress: initial,
};
current = job;
const signal = job.stop.signal;
const report: Report = (phase, doneBytes = 0, totalBytes = 0) => {
if (phase === 'applying') job.interruptible = false;
const next: MaintenanceProgress = { id: request.id, operation: request.operation, phase, doneBytes, totalBytes };
job.progress = next;
publish(next);
};
try {
report('checking');
return await performMaintenance(request, signal, report);
} 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;
publish(null);
}
}
async function performMaintenance(request: MaintenanceRequest, signal: AbortSignal, report: Report): Promise<Copies> {
const { id, operation, steamLocations } = request;
const record = await requireCopy(id);
if (operation === 'set-source') return setCopySource(record, request.sourcePath);
if (operation === 'delete') {
return removeCopy(
record,
{
deleteFiles: request.deleteFiles === true,
restoreStock: request.restoreStock === true,
deleteData: request.deleteData === true,
},
signal,
report,
labServerUses,
);
}
const root = await checkedRoot(record);
const dataPath = await canonicalCopyPath(record.dataPath);
const needsConfirmation = steamLibraryNeedsConfirmation(record, root, dataPath);
if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy');
signal.throwIfAborted();
if (operation !== 'confirm-steam' && needsConfirmation) {
throw new AppError('launch_steam_confirmation_required');
}
switch (operation) {
case 'confirm-steam':
if (!steamLocations || !isAbsolute(steamLocations.copyPath) || !isAbsolute(steamLocations.dataPath) ||
relative(root, steamLocations.copyPath) !== '' || relative(dataPath, steamLocations.dataPath) !== '') {
failLocation('steam_confirmation_mismatch', { root, dataPath, steamLocations });
}
if (!needsConfirmation) return listCopies();
return updateCopyRecord(id, (copy) => ({
...copy, steamLibraryConfirmation: { copyPath: root, dataPath },
}));
case 'check':
return recordCheck(record, record.stockBackupPath);
case 'repair':
return repair(record, root, () => report('applying'));
case 'update':
return updateFromSource(record, root, signal, report);
case 'compact':
return compactCopy(record, root, signal, report);
}
}
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 labServerUses(root: string): Promise<boolean> {
const lab = await readInstalledLab().catch(() => null);
if (!lab || relative(lab.copyPath, root) !== '') return false;
return localServerReady(lab.port);
}
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(),
}));
}