Files
WT-Offline/apps/launcher/src/main/services/launch/launch-controller.ts
T

264 lines
10 KiB
TypeScript

import { readFile } from 'node:fs/promises';
import { createServer } from 'node:net';
import { isAbsolute, join } from 'node:path';
import { app, BrowserWindow, shell } from 'electron';
import { AccountStore, LOOPBACK } from '@wto/server';
import { executableVersion, GAME_FILES, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { GameExit, LaunchState } from '@shared/schemas/launch.ts';
import type { Settings } from '@shared/schemas/settings.ts';
import { getSettings } from '../config/settings-store.ts';
import { decalCachePath } from '../install/decals.ts';
import { canonicalCopyPath, copyPathContains, readInstallRecord } from '../install/install-record.ts';
import { resolveEnabledModsForLaunch } from '../mods/mods-service.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
import { saveBackup } from '../saves/save-archive.ts';
import { buildCopy } from './build-copy.ts';
import { gameProcessRunning } from './game-process.ts';
import { readInstalledLab, runLab, type Lab } from './lab-handoff.ts';
import { localServerStatusUrl } from './local-server.ts';
import { ordinaryLaunchPaths, runOrdinaryLaunch } from './ordinary-launch.ts';
export { gameProcessRunning } from './game-process.ts';
interface LaunchJob {
readonly stop: AbortController;
readonly report: (state: LaunchState) => void;
done: Promise<void>;
copyId?: string;
}
let active: LaunchJob | null = null;
let state: LaunchState = { phase: 'ready' };
export function launchInProgress(): boolean {
return active !== null;
}
export function getLaunchState(): LaunchState {
return state;
}
export function startLaunch(report: LaunchJob['report']): LaunchState {
const previous = active;
if (previous && state.phase !== 'server-running') throw new AppError('launch_busy');
const job: LaunchJob = { stop: new AbortController(), report, done: Promise.resolve() };
active = job;
previous?.stop.abort();
update(job, { phase: 'checking' });
job.done = (async () => {
// A new build may only write after the server from the previous session has stopped.
await previous?.done;
job.stop.signal.throwIfAborted();
await launch(job);
})().catch((error: unknown) => {
if (job.stop.signal.aborted) {
update(job, { phase: 'ready' });
return;
}
const { port } = state;
const context = port === undefined ? {} : { port };
console.error('[launch] launch failed:', error);
const code = error instanceof AppError ? error.code : 'launch_failed';
switch (code) {
case 'launch_port_busy':
update(job, { phase: 'port-busy', ...context });
break;
case 'launch_server_exited':
update(job, { phase: 'server-exited', ...context });
break;
default:
update(job, { phase: 'failed', error: code, ...context });
break;
}
}).finally(() => {
if (active === job) active = null;
});
return state;
}
export function stopLaunch(): Promise<void> | null {
const job = active;
if (!job) return null;
if (!job.stop.signal.aborted) {
update(job, { ...state, phase: 'stopping' });
job.stop.abort();
}
return job.done;
}
export async function openServerStatus(): Promise<void> {
if ((state.phase !== 'running' && state.phase !== 'server-running') || state.port === undefined) {
throw new AppError('launch_server_exited');
}
await shell.openExternal(localServerStatusUrl(state.port));
}
function update(job: LaunchJob, next: LaunchState): void {
if (active !== job) return;
state = job.copyId ? { ...next, copyId: job.copyId } : next;
job.report(state);
}
async function launch(job: LaunchJob): Promise<void> {
if (process.platform !== 'win32') throw new AppError('launch_platform_unsupported');
const signal = job.stop.signal;
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
if (!record) throw new AppError('launch_no_copy');
job.copyId = record.id;
const plan = await planLaunch(job, record, settings);
if (plan === null) return;
const { lab, copyPath, stockPath, dataPath, port, modsDir, enabledModIds } = plan;
await buildForLaunch(job, record, plan, settings);
const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => {
if (signal.aborted) return;
update(job, { phase, port, gameExit });
if (phase === 'running' && settings.afterGameStarts === 'minimize') {
for (const window of BrowserWindow.getAllWindows()) window.minimize();
}
};
if (lab) {
await runLab(lab, stockPath, dataPath, signal, publish);
update(job, { phase: 'ready' });
return;
}
const gameExit = await runOrdinaryLaunch(
copyPath,
dataPath,
port,
settings,
signal,
publish,
{ modsDir, enabledModIds },
);
update(job, { phase: 'game-exited', gameExit });
}
interface LaunchPlan {
readonly lab: Lab | null;
readonly copyPath: string;
readonly stockPath: string;
readonly dataPath: string;
readonly steamLibraryConfirmed: boolean;
readonly port: number;
readonly modsDir: string;
readonly enabledModIds: readonly string[];
}
async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Settings): Promise<LaunchPlan | null> {
const signal = job.stop.signal;
const useLab = !app.isPackaged && settings.developerMode;
if (useLab && (isInSteamLibrary(record.copyPath) || isInSteamLibrary(await canonicalCopyPath(record.copyPath)))) {
throw new AppError('launch_copy_in_steam');
}
const currentVersion = await readVersion(record.copyPath, signal);
if (!currentVersion || currentVersion !== record.gameVersion) {
console.warn(
`[launch] client version changed: recorded=${record.gameVersion ?? 'unknown'}, ` +
`actual=${currentVersion ?? 'missing'} (${record.copyPath})`,
);
update(job, { phase: 'version-changed', actualVersion: currentVersion });
return null;
}
const lab = useLab ? await readInstalledLab() : null;
const { copyPath, stockPath, dataPath, steamLibraryConfirmed } = lab ? {
copyPath: lab.copyPath,
stockPath: settings.labStockPath ?? record.stockBackupPath,
dataPath: settings.labDataPath ?? record.dataPath,
steamLibraryConfirmed: false,
} : await ordinaryLaunchPaths(record);
if (!isAbsolute(stockPath) || !isAbsolute(dataPath)) {
throw new AppError('folder_unreadable', { path: !isAbsolute(stockPath) ? stockPath : dataPath });
}
if (lab && (isInSteamLibrary(copyPath) || isInSteamLibrary(dataPath) || isInSteamLibrary(await canonicalCopyPath(dataPath)))) {
throw new AppError('launch_copy_in_steam');
}
if (copyPathContains(stockPath, dataPath)) throw new AppError('launch_location');
const requestedPort = lab?.port ?? (settings.launchPortMode === 'fixed' ? settings.launchPort : 0);
if (requestedPort) update(job, { phase: 'checking', port: requestedPort });
const [copyVersion, stockVersion, games] = await Promise.all([
lab ? readVersion(copyPath, signal) : currentVersion,
readVersion(stockPath, signal),
gameProcessRunning(signal),
]);
signal.throwIfAborted();
if (!copyVersion || copyVersion !== stockVersion) {
console.warn(
`[launch] copy/stock version mismatch: copy=${copyVersion ?? 'missing'} (${copyPath}), ` +
`stock=${stockVersion ?? 'missing'} (${stockPath})`,
);
if (!lab && !stockVersion) throw new AppError('launch_stock_missing');
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
}
if (games) throw new AppError('launch_game_running');
const { modsDir, enabledMods } = await resolveEnabledModsForLaunch(dataPath, copyVersion);
const enabledModIds = enabledMods.map((mod) => mod.manifest.id);
const port = await selectPort(requestedPort);
return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port, modsDir, enabledModIds };
}
async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise<void> {
const signal = job.stop.signal;
const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed, modsDir, enabledModIds } = plan;
if (settings.autoSaveBackups) {
for (const { userId } of new AccountStore(dataPath).all()) {
signal.throwIfAborted();
await saveBackup({ ...record, dataPath }, userId, 'launch');
}
}
signal.throwIfAborted();
update(job, { phase: 'building', port });
const buildStart = Date.now();
let writtenFiles = 0;
await buildCopy({
kind: 'build',
stockPath,
copyPath,
dataPath,
port,
steamLibraryConfirmed,
...resourcePaths(),
...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}),
hookLogging: settings.loggingEnabled,
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
modsDir,
enabledModIds,
}, signal, (filesWritten, filesTotal, file) => {
writtenFiles = filesWritten;
if (!signal.aborted) update(job, {
phase: 'building', port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }),
});
});
console.info(`[launch] prepared ${writtenFiles} game files for port ${port} in ${Date.now() - buildStart} ms`);
}
async function readVersion(folder: string, signal: AbortSignal): Promise<string | null> {
try {
return executableVersion(await readFile(join(folder, GAME_FILES.executable), { signal }));
} catch (error) {
signal.throwIfAborted();
console.warn('[launch] reading the game version failed:', folder, error);
return null;
}
}
async function selectPort(port: number): Promise<number> {
return new Promise((resolve, reject) => {
const listener = createServer();
listener.once('error', (error: NodeJS.ErrnoException) => reject(
error.code === 'EADDRINUSE' ? new AppError('launch_port_busy') : error,
));
listener.listen(port, LOOPBACK, () => {
const address = listener.address();
listener.close((error) => {
if (error) reject(error);
else if (address && typeof address === 'object') resolve(address.port);
else reject(new AppError('launch_server_failed'));
});
});
});
}