feat(launcher): install offline copies and back up stock files

The launcher's main process can now install the game copy, driven over
IPC by the install wizard to come:

- install:checkPatches builds the copy in memory in a utility process
  (workers/patch-check-worker.ts, a second main entry) and reports the
  patches that do not fit, each marked essential or not. Nothing is
  written.
- install:start checks first, on the stock files the copy would get, so
  a game whose essential patches do not fit is refused before tens of
  gigabytes are copied; other missing patches need the player's
  acceptance. Then, for the copy method, it measures, checks the target
  drive's free space (plus 1 GB) and copies; it keeps the four stock
  files in <copy>/wtoffline/stock, never replacing a file already there;
  and it writes <user data>/install.json. Patched files are written by
  the build at every launch with that launch's port, not here.
- The copy leaves out the top-level folders that hold what the game
  produced while played online (.game_logs, cache, Replays, Screenshots,
  UserMissions). It copies in chunks through streams, so progress moves
  within a large data pack and install:cancel stops at once; it never
  overwrites a file, and after a failure or a cancel it removes what it
  copied, which is safe because the target was new or empty. One failing
  parallel copy stops the others before the cleanup starts.
- Progress goes to the window as event:install-progress, at most every
  250 ms. install:getRecord returns the record and the default data
  folder (<user data>/data).
- New error codes, translated in both languages: not_a_game_folder,
  target_not_usable, steam_library_not_confirmed, not_enough_space,
  essential_patches_unavailable, missing_features_not_accepted,
  patch_check_failed, copy_failed, install_cancelled, install_busy.

Checked with the launcher typecheck and build, and the calls made from a
running launcher window on a 2 GB test game folder holding the real
stock files: the check (12 exe and 35 GUI patches ready), a copy
install (player data folders left out, stock files backed up, record
written, 51 progress events), a second install into the same folder
(not_empty), a cancel 36 MB into a copy (install_cancelled, the copy
removed), an in-place install of the copy (its backup used) and a
folder that is not a game.
This commit is contained in:
N0VAN0M4LY committed 2026-11-29 05:03:40 +08:00
1 parent ab0d3b1f30
commit 3dcf7bb062
14 files changed
+629 -3

No files matched your search

+7
View File
@@ -4,6 +4,8 @@ import { getSettings, updateSettings } from '../services/config/settings-store.t
import { measureFolder } from '../services/game-folder/folder-size.ts';
import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts';
import { inspectTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
import { cancelInstall, checkGameFolder, installGame } from '../services/install/install-game.ts';
import { defaultDataPath, readInstallRecord } from '../services/install/install-record.ts';
import { broadcast, handle } from './register.ts';
/** Registers the handler of every contract channel. One line per channel; the work is in services/. */
@@ -34,6 +36,11 @@ export function registerIpcHandlers(): void {
}
});
handle('install:checkPatches', ({ gamePath, dataPath }) => checkGameFolder(gamePath, dataPath));
handle('install:start', (request) => installGame(request, (progress) => broadcast('event:install-progress', progress)));
handle('install:cancel', () => ({ cancelled: cancelInstall() }));
handle('install:getRecord', async () => ({ record: await readInstallRecord(), defaultDataPath: defaultDataPath() }));
handle('settings:get', () => getSettings());
handle('settings:update', async (patch) => {
const settings = await updateSettings(patch);
@@ -0,0 +1,126 @@
import { createReadStream, createWriteStream } from 'node:fs';
import { lstat, mkdir, readdir, rm } from 'node:fs/promises';
import { join, relative } from 'node:path';
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
/**
* Copy a War Thunder installation into a new or empty folder (install method "copy"). The stock
* folder is only read. Nothing in the target is overwritten (the target was checked to be empty).
*/
/**
* Top-level folders of an installation that hold what the game produced while the player played
* online, not the game itself: logs, the web content cache, replays, screenshots and the player's
* own missions. The offline copy does not take the online game's data (working rules 18); the
* game creates these folders again when it needs them.
*/
const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screenshots', 'usermissions']);
interface CopyEntry {
readonly relativePath: string;
readonly bytes: number;
}
export interface CopyPlan {
readonly files: readonly CopyEntry[];
readonly folders: readonly string[];
readonly totalBytes: number;
}
export interface CopyProgress {
readonly doneBytes: number;
readonly doneFiles: number;
}
/** Every file and folder to copy, relative to `source`. Links and junctions are not followed. */
export async function planCopy(source: string): Promise<CopyPlan> {
const files: CopyEntry[] = [];
const folders: string[] = [];
let totalBytes = 0;
const pending = [source];
while (pending.length) {
const folder = pending.pop()!;
for (const entry of await readdir(folder, { withFileTypes: true })) {
const path = join(folder, entry.name);
if (folder === source && PLAYER_DATA_FOLDERS.has(entry.name.toLowerCase())) continue;
if (entry.isDirectory()) {
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;
}
}
}
return { files, folders, totalBytes };
}
/** How many files are copied at the same time; enough to keep a disk busy without thrashing it. */
const PARALLEL_COPIES = 4;
/**
* Copies the planned files in chunks, so progress moves with every chunk and an abort of
* `signal` stops even a multi-gigabyte data pack at once (then the abort reason is thrown).
* Never overwrites a file in `target`.
*/
export async function copyPlannedFiles(
source: string,
target: string,
plan: CopyPlan,
signal: AbortSignal,
onProgress: (progress: CopyProgress) => void,
): Promise<void> {
await mkdir(target, { recursive: true });
for (const folder of plan.folders) await mkdir(join(target, folder), { recursive: true });
let next = 0;
let doneBytes = 0;
let doneFiles = 0;
const countBytes = (): Transform => new Transform({
transform(chunk: Buffer, _encoding, callback) {
doneBytes += chunk.length;
onProgress({ doneBytes, doneFiles });
callback(null, chunk);
},
});
// One failing copy stops the others, and this returns only once all of them have stopped, so a
// caller cleaning up after an error never races a copy still writing.
const stop = new AbortController();
const stopSignal = AbortSignal.any([signal, stop.signal]);
const copyNext = async (): Promise<void> => {
try {
while (next < plan.files.length) {
stopSignal.throwIfAborted();
const file = plan.files[next++]!;
await pipeline(
createReadStream(join(source, file.relativePath)),
countBytes(),
// 'wx': fail instead of overwriting a file that is already there.
createWriteStream(join(target, file.relativePath), { flags: 'wx' }),
{ signal: stopSignal },
);
doneFiles += 1;
onProgress({ doneBytes, doneFiles });
}
} catch (error) {
stop.abort(error);
throw error;
}
};
const results = await Promise.allSettled(Array.from({ length: PARALLEL_COPIES }, copyNext));
const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');
if (failed) throw failed.reason;
}
/**
* Removes what an interrupted copy left in `target`. Only for a target that was new or empty
* when the copy started, so everything in it came from the copy.
*/
export async function removeInterruptedCopy(target: string, targetExisted: boolean): Promise<void> {
if (!targetExisted) {
await rm(target, { recursive: true, force: true });
return;
}
for (const entry of await readdir(target)) await rm(join(target, entry), { recursive: true, force: true });
}
@@ -0,0 +1,160 @@
import { access, mkdir } from 'node:fs/promises';
import { AppError } from '@shared/errors.ts';
import type { InstallProgress, InstallRecord, InstallRequest, PatchCheck } from '@shared/schemas/install.ts';
import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts';
import { inspectTargetFolder } from '../game-folder/inspect-target-folder.ts';
import { copyPlannedFiles, planCopy, removeInterruptedCopy } from './copy-game.ts';
import { writeInstallRecord } from './install-record.ts';
import { checkPatches } from './patch-check.ts';
import { backUpStockFiles, stockBackupPath } from './stock-backup.ts';
/**
* Install the offline version: check the patches against the player's game,
* copy it (method "copy"), keep its stock files in the copy's backup folder and record the
* installation. The patched files are written by the build at every launch, with that launch's
* port; installing writes no patched file.
*
* The patches are checked first, on the stock files the copy would get, so a game whose
* essential patches do not fit is refused before 90 GB are copied.
*/
/** Room kept free on the target drive beyond the copy itself, for the game's caches and logs. */
const SPARE_BYTES = 1024 ** 3;
/** At most this often a progress event goes to the window. */
const PROGRESS_INTERVAL_MS = 250;
let running: AbortController | null = null;
export async function installGame(request: InstallRequest, onProgress: (progress: InstallProgress) => void): Promise<InstallRecord> {
if (running) throw new AppError('install_busy');
const controller = new AbortController();
running = controller;
try {
return await install(request, controller.signal, throttled(onProgress));
} finally {
running = null;
}
}
/** Stops a running copy at the next file; returns whether an installation was running. */
export function cancelInstall(): boolean {
if (!running) return false;
running.abort();
return true;
}
/**
* The stock files a check of `gameFolder` starts from: its backup folder when it already has one
* (a folder installed before, whose own files may be patched), otherwise its own files.
*/
export async function stockFolderOf(gameFolder: string): Promise<string> {
const backup = stockBackupPath(gameFolder);
try {
await access(backup);
return backup;
} catch {
return gameFolder;
}
}
/** Which patches fit the game in `gameFolder`, for the window to show before installing. */
export async function checkGameFolder(gameFolder: string, dataPath: string): Promise<PatchCheck> {
await requireGameFolder(gameFolder);
return checkPatches(await stockFolderOf(gameFolder), dataPath);
}
async function install(request: InstallRequest, signal: AbortSignal, report: (progress: InstallProgress) => void): Promise<InstallRecord> {
const gameFolder = request.method === 'copy' ? request.sourcePath : request.gamePath;
const game = await requireGameFolder(gameFolder);
const copyPath = request.method === 'copy' ? request.copyPath : request.gamePath;
const target = request.method === 'copy' ? await inspectTargetFolder(copyPath, gameFolder) : null;
if (target?.problem) throw new AppError('target_not_usable', { problem: target.problem });
const inSteamLibrary = target ? target.inSteamLibrary : game.inSteamLibrary;
if (inSteamLibrary && !request.steamLibraryConfirmed) throw new AppError('steam_library_not_confirmed');
report({ phase: 'checking', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
await mkdir(request.dataPath, { recursive: true });
const check = await checkPatches(await stockFolderOf(gameFolder), request.dataPath);
const essential = check.unavailable.filter((patch) => patch.essential);
if (essential.length) throw new AppError('essential_patches_unavailable', { patches: essential.map((patch) => patch.patchId).join(', ') });
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);
report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const stockBackup = await backUpStockFiles(copyPath);
report({ phase: 'recording', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const record: InstallRecord = {
method: request.method,
copyPath,
dataPath: request.dataPath,
stockBackupPath: stockBackup,
gameVersion: game.version,
unavailablePatches: check.unavailable,
installedAt: new Date().toISOString(),
};
await writeInstallRecord(record);
return record;
}
async function copyGame(
source: string,
target: string,
freeBytes: number | null,
signal: AbortSignal,
report: (progress: InstallProgress) => void,
): Promise<void> {
report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 });
const plan = await planCopy(source);
if (freeBytes !== null && freeBytes < plan.totalBytes + SPARE_BYTES) {
throw new AppError('not_enough_space', { neededGb: gigabytes(plan.totalBytes + SPARE_BYTES), freeGb: gigabytes(freeBytes) });
}
const targetExisted = await exists(target);
const totals = { totalBytes: plan.totalBytes, totalFiles: plan.files.length };
report({ phase: 'copying', doneBytes: 0, doneFiles: 0, ...totals });
try {
await copyPlannedFiles(source, target, plan, signal, (done) => report({ phase: 'copying', ...done, ...totals }));
} 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');
console.error('[install] copying failed:', error);
throw new AppError('copy_failed');
}
}
async function requireGameFolder(path: string) {
const game = await inspectGameFolder(path);
if (game.missingFiles.length) throw new AppError('not_a_game_folder', { path });
return game;
}
/** Passes on the first and last report of each phase and at most one per interval in between. */
function throttled(onProgress: (progress: InstallProgress) => void): (progress: InstallProgress) => void {
let lastSent = 0;
let lastPhase = '';
return (progress) => {
const now = Date.now();
const finished = progress.totalFiles > 0 && progress.doneFiles === progress.totalFiles;
if (progress.phase !== lastPhase || finished || now - lastSent >= PROGRESS_INTERVAL_MS) {
lastSent = now;
lastPhase = progress.phase;
onProgress(progress);
}
};
}
function gigabytes(bytes: number): string {
return (bytes / 1024 ** 3).toFixed(1);
}
async function exists(path: string): Promise<boolean> {
try {
await access(path);
return true;
} catch {
return false;
}
}
@@ -0,0 +1,36 @@
import { join } from 'node:path';
import { app } from 'electron';
import { InstallRecordSchema, type InstallRecord } from '@shared/schemas/install.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
/** The installed game copy, `<user data>/install.json`; null before the first installation. */
function recordPath(): string {
return join(app.getPath('userData'), 'install.json');
}
export async function readInstallRecord(): Promise<InstallRecord | null> {
let raw: unknown;
try {
raw = await readJsonOr(recordPath(), null);
} catch (error) {
console.warn('[install] install.json is unreadable:', error);
return null;
}
if (raw === null) return null;
const parsed = InstallRecordSchema.safeParse(raw);
if (!parsed.success) {
console.warn('[install] install.json did not validate:', parsed.error.issues);
return null;
}
return parsed.data;
}
export async function writeInstallRecord(record: InstallRecord): Promise<void> {
await writeJsonAtomic(recordPath(), InstallRecordSchema.parse(record));
}
/** The data folder offered when the player does not choose one. */
export function defaultDataPath(): string {
return join(app.getPath('userData'), 'data');
}
@@ -0,0 +1,41 @@
import { join } from 'node:path';
import { utilityProcess } from 'electron';
import { AppError } from '@shared/errors.ts';
import type { PatchCheck } from '@shared/schemas/install.ts';
import type { PatchCheckReply, PatchCheckRequest } from '../../workers/patch-check-protocol.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
/**
* Which patches fit the stock files in `stockFolder`, worked out in a utility process
* (workers/patch-check-worker.ts). Nothing is written.
*/
export function checkPatches(stockFolder: string, dataFolder: string): Promise<PatchCheck> {
const resources = resourcePaths();
const request: PatchCheckRequest = {
stockFolder,
dataFolder,
exePatches: resources.exePatches,
guiPatches: resources.guiPatches,
networkHookLibrary: resources.networkHookLibrary,
};
return new Promise((resolve, reject) => {
const worker = utilityProcess.fork(join(import.meta.dirname, 'patch-check-worker.js'), [], { serviceName: 'WTOffline patch check' });
let answered = false;
worker.once('message', (reply: PatchCheckReply) => {
answered = true;
worker.kill();
if (reply.ok) {
resolve(reply.check);
} else {
console.error('[install] the patch check failed:', reply.error);
reject(new AppError('patch_check_failed'));
}
});
worker.once('exit', (code) => {
if (answered) return;
console.error('[install] the patch check process ended without an answer, exit code', code);
reject(new AppError('patch_check_failed'));
});
worker.postMessage(request);
});
}
@@ -0,0 +1,40 @@
import { constants } from 'node:fs';
import { access, copyFile, mkdir } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { GAME_FILES } from '@wto/patcher';
/**
* The stock files every build starts from, kept inside the game copy: the three data packs and
* the executable the build replaces. After installation the launcher never reads the player's
* online installation again, so a Steam update of it cannot change the offline copy unnoticed;
* for an in-place installation these are also the files to put back to undo it.
*/
export const STOCK_BACKUP_FOLDER = join('wtoffline', 'stock');
export function stockBackupPath(copyFolder: string): string {
return join(copyFolder, STOCK_BACKUP_FOLDER);
}
/**
* Copies each stock file from the copy into the backup folder, unless the backup already has it:
* a backed-up file is never replaced, because the copy's own file may be a patched one by then.
*/
export async function backUpStockFiles(copyFolder: string): Promise<string> {
const backup = stockBackupPath(copyFolder);
for (const file of Object.values(GAME_FILES)) {
const kept = join(backup, file);
if (await exists(kept)) continue;
await mkdir(dirname(kept), { recursive: true });
await copyFile(join(copyFolder, file), kept, constants.COPYFILE_EXCL);
}
return backup;
}
async function exists(path: string): Promise<boolean> {
try {
await access(path);
return true;
} catch {
return false;
}
}
@@ -0,0 +1,16 @@
import type { PatchCheck } from '@shared/schemas/install.ts';
/** What the main process sends the patch check worker: everything the build needs. */
export interface PatchCheckRequest {
/** Folder holding the four stock files (the copy's backup folder). */
readonly stockFolder: string;
/** The local server's data folder: its store tuning names the packs that get bundle GUIDs. */
readonly dataFolder: string;
readonly exePatches: string;
readonly guiPatches: string;
readonly networkHookLibrary: string;
}
export type PatchCheckReply =
| { readonly ok: true; readonly check: PatchCheck }
| { readonly ok: false; readonly error: string };
@@ -0,0 +1,47 @@
/**
* Utility process: build the game copy in memory and report which patches fit, writing nothing.
* The build parses a 130 MB executable and three data packs, which would stall the window if it
* ran in the main process. One request per process; the main process ends it after the reply.
*/
import { readFileSync } from 'node:fs';
import type { MessageEvent } from 'electron';
import { buildGameCopy, ESSENTIAL_FEATURES, readStockGameFiles } from '@wto/patcher';
import { multiVehiclePackIds } from '@wto/server';
import type { PatchCheck } from '@shared/schemas/install.ts';
import type { PatchCheckReply, PatchCheckRequest } from './patch-check-protocol.ts';
/** Any valid port: the port does not decide which patches fit. */
const CHECK_PORT = 47000;
process.parentPort.once('message', (event: MessageEvent) => {
let reply: PatchCheckReply;
try {
reply = { ok: true, check: checkPatches(event.data as PatchCheckRequest) };
} catch (error) {
reply = { ok: false, error: error instanceof Error ? (error.stack ?? error.message) : String(error) };
}
process.parentPort.postMessage(reply);
});
function checkPatches(request: PatchCheckRequest): PatchCheck {
const build = buildGameCopy({
stock: readStockGameFiles(request.stockFolder),
port: CHECK_PORT,
exePatches: request.exePatches,
guiPatches: request.guiPatches,
networkHookLibrary: readFileSync(request.networkHookLibrary),
multiVehiclePackIds: multiVehiclePackIds(request.dataFolder, () => undefined),
placeholderDecals: true,
});
const failures = [...build.exePatches.failures, ...build.guiPatches.failures];
return {
exePatchesReady: build.exePatches.applied.length,
guiPatchesReady: build.guiPatches.applied.length,
unavailable: failures.map((failure) => ({
patchId: failure.patchId,
features: [...failure.features],
reason: failure.reason,
essential: failure.features.some((feature) => ESSENTIAL_FEATURES.has(feature)),
})),
};
}