feat(launcher): implement gated standard launch
Build the selected copy for its port, wait for the local server, and manage the game and server lifecycles. Keep standard launch disabled pending isolation verification. Verified both type checks, the launcher build, and the launch lifecycle against a temporary copy and a stand-in executable.
This commit is contained in:
1 parent
2a97b0d46c
commit
c1dea23955
19 files changed
+522
-105
No files matched your search
@@ -11,6 +11,7 @@ import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
|
||||
*/
|
||||
|
||||
let cached: Settings | null = null;
|
||||
let pending: Promise<void> = Promise.resolve();
|
||||
|
||||
function settingsPath(): string {
|
||||
return join(app.getPath('userData'), 'settings.json');
|
||||
@@ -35,17 +36,21 @@ export async function getSettings(): Promise<Settings> {
|
||||
return cached;
|
||||
}
|
||||
|
||||
export async function updateSettings(patch: SettingsPatch): Promise<Settings> {
|
||||
const current = await getSettings();
|
||||
const merged = SettingsSchema.parse({ ...current, ...definedFields(patch) });
|
||||
try {
|
||||
await writeJsonAtomic(settingsPath(), merged);
|
||||
} catch (error) {
|
||||
console.error('[settings] write failed:', error);
|
||||
throw new AppError('settings_write_failed');
|
||||
}
|
||||
cached = merged;
|
||||
return merged;
|
||||
export function updateSettings(patch: SettingsPatch): Promise<Settings> {
|
||||
const operation = pending.then(async () => {
|
||||
const current = await getSettings();
|
||||
const merged = SettingsSchema.parse({ ...current, ...definedFields(patch) });
|
||||
try {
|
||||
await writeJsonAtomic(settingsPath(), merged);
|
||||
} catch (error) {
|
||||
console.error('[settings] write failed:', error);
|
||||
throw new AppError('settings_write_failed');
|
||||
}
|
||||
cached = merged;
|
||||
return merged;
|
||||
});
|
||||
pending = operation.then(() => undefined, () => undefined);
|
||||
return operation;
|
||||
}
|
||||
|
||||
/** The patch without the fields it leaves out, so they do not overwrite current values. */
|
||||
|
||||
@@ -15,7 +15,8 @@ import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, upda
|
||||
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 { readInstalledLab } from '../launch/lab-handoff.ts';
|
||||
import { localServerReady } from '../launch/local-server.ts';
|
||||
import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts';
|
||||
|
||||
let current: { stop: AbortController; interruptible: boolean } | null = null;
|
||||
@@ -130,12 +131,7 @@ async function safeFolder(path: string): Promise<string> {
|
||||
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;
|
||||
}
|
||||
return localServerReady(lab.port);
|
||||
}
|
||||
|
||||
async function recordCheck(record: InstallRecord, folder: string): Promise<Copies> {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { execFile, spawn } from 'node:child_process';
|
||||
import { join } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { GAME_FILES } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { ORDINARY_LAUNCH_ENABLED } from '@shared/schemas/launch.ts';
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const OFFLINE_ARGUMENTS = ['-forcestart', '-nobeac', '-crashpad-disable-upload'];
|
||||
|
||||
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 async function runGameProcess(
|
||||
copyPath: string, additionalArguments: readonly string[], signal: AbortSignal, onStart: () => void,
|
||||
): Promise<void> {
|
||||
if (!ORDINARY_LAUNCH_ENABLED || process.platform !== 'win32') throw new AppError('launch_disabled');
|
||||
if (await gameProcessRunning(signal)) throw new AppError('launch_game_running');
|
||||
signal.throwIfAborted();
|
||||
const child = spawn(join(copyPath, GAME_FILES.executable), [...OFFLINE_ARGUMENTS, ...additionalArguments], {
|
||||
cwd: copyPath, shell: false, stdio: 'ignore',
|
||||
});
|
||||
const stop = (): void => { child.kill(); };
|
||||
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.once('spawn', () => {
|
||||
if (signal.aborted) stop();
|
||||
else onStart();
|
||||
});
|
||||
child.once('error', (error) => {
|
||||
console.error('[game] process error:', error);
|
||||
reject(new AppError('launch_game_failed'));
|
||||
});
|
||||
child.once('close', (code, reason) => {
|
||||
if (code === 0 || signal.aborted) resolve();
|
||||
else {
|
||||
console.error('[game] process exited:', code ?? reason);
|
||||
reject(new AppError('launch_game_failed'));
|
||||
}
|
||||
});
|
||||
signal.addEventListener('abort', stop, { once: true });
|
||||
});
|
||||
} finally {
|
||||
signal.removeEventListener('abort', stop);
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,8 @@ import { lstat, readFile, realpath, writeFile } from 'node:fs/promises';
|
||||
import { isAbsolute, join, relative, resolve } from 'node:path';
|
||||
import { app } from 'electron';
|
||||
import { z } from 'zod';
|
||||
import { HEALTH_PATH } from '@wto/server';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { localServerReady } from './local-server.ts';
|
||||
import { forwardProcessOutput } from './process-output.ts';
|
||||
|
||||
const Configuration = z.object({
|
||||
@@ -18,7 +18,6 @@ const Status = z.object({
|
||||
message: z.string(),
|
||||
guardExitCode: z.number().nullable().optional(),
|
||||
});
|
||||
const Health = z.object({ app: z.literal('wto-server'), pid: z.number() });
|
||||
|
||||
export interface Lab {
|
||||
readonly installPath: string;
|
||||
@@ -58,10 +57,6 @@ export async function readInstalledLab(): Promise<Lab> {
|
||||
}
|
||||
}
|
||||
|
||||
export function labStatusUrl(port: number): string {
|
||||
return `http://127.0.0.1:${port}${HEALTH_PATH}`;
|
||||
}
|
||||
|
||||
async function readStatus(lab: Lab): Promise<z.output<typeof Status> | null> {
|
||||
try {
|
||||
return Status.parse(JSON.parse(await readFile(join(lab.controlPath, 'status.json'), 'utf8')));
|
||||
@@ -70,15 +65,6 @@ async function readStatus(lab: Lab): Promise<z.output<typeof Status> | null> {
|
||||
}
|
||||
}
|
||||
|
||||
async function isReady(port: number, pid: number): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(labStatusUrl(port), { signal: AbortSignal.timeout(900) });
|
||||
return response.ok && Health.parse(await response.json()).pid === pid;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function stopGame(lab: Lab): Promise<void> {
|
||||
await writeFile(join(lab.controlPath, 'stop-request'), '', { flag: 'wx' }).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== 'EEXIST') throw error;
|
||||
@@ -145,7 +131,7 @@ export async function runLab(
|
||||
return;
|
||||
}
|
||||
checking = true;
|
||||
void isReady(lab.port, serverPid).then((ready) => {
|
||||
void localServerReady(lab.port, serverPid).then((ready) => {
|
||||
if (!running || processClosed) return;
|
||||
failures = ready ? 0 : failures + 1;
|
||||
if (failures < 3) return;
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
import { execFile } from 'node:child_process';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { createServer } from 'node:net';
|
||||
import { isAbsolute, join, relative } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { BrowserWindow, shell } from 'electron';
|
||||
import { AccountStore } from '@wto/server';
|
||||
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 { LaunchState } from '@shared/schemas/launch.ts';
|
||||
import { ORDINARY_LAUNCH_ENABLED, type LaunchState } from '@shared/schemas/launch.ts';
|
||||
import { getSettings } from '../config/settings-store.ts';
|
||||
import { readInstallRecord } from '../install/install-record.ts';
|
||||
import { copyPathContains, readInstallRecord } from '../install/install-record.ts';
|
||||
import { resourcePaths } from '../resources/resource-paths.ts';
|
||||
import { saveBackup } from '../saves/save-archive.ts';
|
||||
import { buildCopy } from './build-copy.ts';
|
||||
import { labStatusUrl, readInstalledLab, runLab } from './lab-handoff.ts';
|
||||
import { gameProcessRunning } from './game-process.ts';
|
||||
import { readInstalledLab, runLab } from './lab-handoff.ts';
|
||||
import { localServerStatusUrl } from './local-server.ts';
|
||||
import { ordinaryLaunchPaths, runOrdinaryLaunch } from './ordinary-launch.ts';
|
||||
|
||||
const execute = promisify(execFile);
|
||||
export { gameProcessRunning } from './game-process.ts';
|
||||
|
||||
interface LaunchJob {
|
||||
readonly stop: AbortController;
|
||||
@@ -31,30 +32,31 @@ 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;
|
||||
}
|
||||
|
||||
export function startLaunch(report: LaunchJob['report']): LaunchState {
|
||||
if (active) throw new AppError('launch_busy');
|
||||
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 = launch(job).catch((error: unknown) => {
|
||||
const port = state.port;
|
||||
const context = port === undefined ? {} : { port };
|
||||
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_lab_failed';
|
||||
const code = error instanceof AppError ? error.code : 'launch_failed';
|
||||
switch (code) {
|
||||
case 'launch_port_busy':
|
||||
update(job, { phase: 'port-busy', ...context });
|
||||
@@ -67,7 +69,7 @@ export function startLaunch(report: LaunchJob['report']): LaunchState {
|
||||
break;
|
||||
}
|
||||
}).finally(() => {
|
||||
active = null;
|
||||
if (active === job) active = null;
|
||||
});
|
||||
return state;
|
||||
}
|
||||
@@ -83,11 +85,14 @@ export function stopLaunch(): Promise<void> | null {
|
||||
}
|
||||
|
||||
export async function openServerStatus(): Promise<void> {
|
||||
if (state.phase !== 'running' || state.port === undefined) throw new AppError('launch_server_exited');
|
||||
await shell.openExternal(labStatusUrl(state.port));
|
||||
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);
|
||||
}
|
||||
@@ -97,7 +102,10 @@ async function launch(job: LaunchJob): Promise<void> {
|
||||
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
|
||||
if (!record) throw new AppError('launch_no_copy');
|
||||
job.copyId = record.id;
|
||||
if (!settings.developerMode) throw new AppError('launch_lab_required');
|
||||
const useLab = !app.isPackaged && settings.developerMode;
|
||||
if (!useLab && !ORDINARY_LAUNCH_ENABLED) {
|
||||
throw new AppError(app.isPackaged ? 'launch_disabled' : 'launch_lab_required');
|
||||
}
|
||||
if (isInSteamLibrary(record.copyPath)) throw new AppError('launch_copy_in_steam');
|
||||
const currentVersion = await readVersion(record.copyPath, signal);
|
||||
if (!currentVersion || currentVersion !== record.gameVersion) {
|
||||
@@ -105,26 +113,31 @@ async function launch(job: LaunchJob): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
const lab = await readInstalledLab();
|
||||
const stockPath = settings.labStockPath ?? record.stockBackupPath;
|
||||
const dataPath = settings.labDataPath ?? record.dataPath;
|
||||
const lab = useLab ? await readInstalledLab() : null;
|
||||
const { copyPath, stockPath, dataPath } = lab ? {
|
||||
copyPath: lab.copyPath,
|
||||
stockPath: settings.labStockPath ?? record.stockBackupPath,
|
||||
dataPath: settings.labDataPath ?? record.dataPath,
|
||||
} : await ordinaryLaunchPaths(record);
|
||||
if (!isAbsolute(stockPath) || !isAbsolute(dataPath)) {
|
||||
throw new AppError('folder_unreadable', { path: !isAbsolute(stockPath) ? stockPath : dataPath });
|
||||
}
|
||||
const relativeData = relative(stockPath, dataPath);
|
||||
if (isInSteamLibrary(dataPath) || (!isAbsolute(relativeData) && !relativeData.startsWith('..'))) {
|
||||
if (isInSteamLibrary(dataPath) || copyPathContains(stockPath, dataPath)) {
|
||||
throw new AppError('launch_copy_in_steam');
|
||||
}
|
||||
update(job, { phase: 'checking', port: lab.port });
|
||||
const [labVersion, stockVersion, games] = await Promise.all([
|
||||
readVersion(lab.copyPath, signal),
|
||||
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 (!labVersion || labVersion !== stockVersion) throw new AppError('launch_lab_version');
|
||||
if (!copyVersion || copyVersion !== stockVersion) {
|
||||
throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version');
|
||||
}
|
||||
if (games) throw new AppError('launch_game_running');
|
||||
await checkPort(lab.port);
|
||||
const port = await selectPort(requestedPort);
|
||||
if (settings.autoSaveBackups) {
|
||||
for (const { userId } of new AccountStore(dataPath).all()) {
|
||||
signal.throwIfAborted();
|
||||
@@ -132,27 +145,30 @@ async function launch(job: LaunchJob): Promise<void> {
|
||||
}
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
update(job, { phase: 'building', port: lab.port });
|
||||
update(job, { phase: 'building', port });
|
||||
await buildCopy({
|
||||
kind: 'build',
|
||||
stockPath,
|
||||
copyPath: lab.copyPath,
|
||||
copyPath,
|
||||
dataPath,
|
||||
port: lab.port,
|
||||
port,
|
||||
...resourcePaths(),
|
||||
acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId),
|
||||
}, signal, (filesWritten, filesTotal, file) => {
|
||||
if (!signal.aborted) update(job, {
|
||||
phase: 'building', port: lab.port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }),
|
||||
phase: 'building', port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }),
|
||||
});
|
||||
});
|
||||
|
||||
await runLab(lab, stockPath, dataPath, signal, (phase) => {
|
||||
if (!signal.aborted) update(job, { phase, port: lab.port });
|
||||
if (phase === 'running' && !signal.aborted && settings.afterGameStarts === 'minimize') {
|
||||
const publish = (phase: LaunchState['phase']): void => {
|
||||
if (signal.aborted) return;
|
||||
update(job, { phase, port });
|
||||
if (phase === 'running' && settings.afterGameStarts === 'minimize') {
|
||||
for (const window of BrowserWindow.getAllWindows()) window.minimize();
|
||||
}
|
||||
});
|
||||
};
|
||||
if (lab) await runLab(lab, stockPath, dataPath, signal, publish);
|
||||
else await runOrdinaryLaunch(copyPath, dataPath, port, settings, signal, publish);
|
||||
update(job, { phase: 'ready' });
|
||||
}
|
||||
|
||||
@@ -166,12 +182,19 @@ async function readVersion(folder: string, signal: AbortSignal): Promise<string
|
||||
}
|
||||
}
|
||||
|
||||
async function checkPort(port: number): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
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, '127.0.0.1', () => listener.close((error) => error ? reject(error) : resolve()));
|
||||
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'));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { once } from 'node:events';
|
||||
import { join } from 'node:path';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { utilityProcess } from 'electron';
|
||||
import { z } from 'zod';
|
||||
import { HEALTH_PATH, LOOPBACK, type ServerOptions } from '@wto/server';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import type { ServerWorkerStatus } from '../../workers/server-worker.ts';
|
||||
import { forwardProcessOutput } from './process-output.ts';
|
||||
|
||||
const Health = z.object({ app: z.literal('wto-server'), pid: z.number() });
|
||||
|
||||
interface LocalServer {
|
||||
readonly exited: Promise<number>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export function localServerStatusUrl(port: number): string {
|
||||
return `http://${LOOPBACK}:${port}${HEALTH_PATH}`;
|
||||
}
|
||||
|
||||
export async function localServerReady(port: number, pid?: number, signal?: AbortSignal): Promise<boolean> {
|
||||
const deadline = AbortSignal.timeout(900);
|
||||
try {
|
||||
const response = await fetch(localServerStatusUrl(port), {
|
||||
redirect: 'error', signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
|
||||
});
|
||||
if (!response.ok) return false;
|
||||
const health = Health.parse(await response.json());
|
||||
return pid === undefined || health.pid === pid;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function startLocalServer(
|
||||
{ gameFolder, dataFolder, port }: Omit<ServerOptions, 'report'>, signal: AbortSignal,
|
||||
): Promise<LocalServer> {
|
||||
signal.throwIfAborted();
|
||||
const worker = utilityProcess.fork(join(import.meta.dirname, 'server-worker.js'), [gameFolder, dataFolder, String(port)], {
|
||||
serviceName: 'WTOffline local server',
|
||||
stdio: 'pipe',
|
||||
});
|
||||
forwardProcessOutput(worker.stdout, 'server', 'info');
|
||||
forwardProcessOutput(worker.stderr, 'server', 'error');
|
||||
|
||||
let ended = false;
|
||||
const exited = new Promise<number>((resolve) => worker.once('exit', (code) => {
|
||||
ended = true;
|
||||
resolve(code);
|
||||
}));
|
||||
worker.on('error', (type, location) => console.error('[server] utility process error:', type, location));
|
||||
|
||||
const stop = async (graceful: boolean): Promise<void> => {
|
||||
if (!ended && graceful) {
|
||||
worker.postMessage('close');
|
||||
await Promise.race([exited, delay(3000, undefined, { ref: false })]);
|
||||
}
|
||||
if (!ended && !worker.kill() && worker.pid === undefined) {
|
||||
worker.once('spawn', () => worker.kill());
|
||||
}
|
||||
await exited;
|
||||
};
|
||||
|
||||
const startup = AbortSignal.any([signal, AbortSignal.timeout(60_000)]);
|
||||
let listening = false;
|
||||
try {
|
||||
const reply: ServerWorkerStatus = await Promise.race([
|
||||
once(worker, 'message', { signal: startup }).then(([status]) => status as ServerWorkerStatus),
|
||||
exited.then(() => 'failed' as const),
|
||||
]);
|
||||
if (reply === 'port-busy') throw new AppError('launch_port_busy');
|
||||
const pid = worker.pid;
|
||||
if (reply !== 'listening' || pid === undefined) throw new AppError('launch_server_failed');
|
||||
listening = true;
|
||||
while (!ended) {
|
||||
startup.throwIfAborted();
|
||||
if (await localServerReady(port, pid, startup)) {
|
||||
startup.throwIfAborted();
|
||||
if (!ended) return { exited, close: () => stop(true) };
|
||||
break;
|
||||
}
|
||||
await delay(150, undefined, { signal: startup });
|
||||
}
|
||||
throw new AppError('launch_server_failed');
|
||||
} catch (error) {
|
||||
await stop(listening);
|
||||
signal.throwIfAborted();
|
||||
console.error('[server] startup failed:', error);
|
||||
throw error instanceof AppError ? error : new AppError('launch_server_failed');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { once } from 'node:events';
|
||||
import { isAbsolute, join, relative } from 'node:path';
|
||||
import { GAME_FILES, isInSteamLibrary } from '@wto/patcher';
|
||||
import { AppError } from '@shared/errors.ts';
|
||||
import { parseLaunchArguments } from '@shared/launch-arguments.ts';
|
||||
import { ORDINARY_LAUNCH_ENABLED } from '@shared/schemas/launch.ts';
|
||||
import type { InstallRecord } from '@shared/schemas/install.ts';
|
||||
import type { Settings } from '@shared/schemas/settings.ts';
|
||||
import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts';
|
||||
import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts';
|
||||
import { runGameProcess } from './game-process.ts';
|
||||
import { startLocalServer } from './local-server.ts';
|
||||
|
||||
export async function ordinaryLaunchPaths(record: InstallRecord) {
|
||||
const paths = [record.copyPath, record.stockBackupPath, record.dataPath] as const;
|
||||
if (paths.some((path) => !isAbsolute(path))) throw new AppError('launch_location');
|
||||
const [copyPath, stockPath, dataPath] = await Promise.all([
|
||||
canonicalCopyPath(record.copyPath), canonicalCopyPath(record.stockBackupPath), canonicalCopyPath(record.dataPath),
|
||||
]);
|
||||
const executable = await canonicalCopyPath(join(copyPath, GAME_FILES.executable));
|
||||
const source = record.sourcePath;
|
||||
if (relative(copyPath, stockPath).toLowerCase() !== STOCK_BACKUP_FOLDER.toLowerCase() ||
|
||||
relative(copyPath, executable).toLowerCase() !== GAME_FILES.executable.toLowerCase() ||
|
||||
copyPathContains(stockPath, dataPath) ||
|
||||
(source !== null && [copyPath, dataPath].some((path) => copyPathContains(source, path)))) {
|
||||
throw new AppError('launch_location');
|
||||
}
|
||||
if (isInSteamLibrary(copyPath) || isInSteamLibrary(dataPath)) throw new AppError('launch_copy_in_steam');
|
||||
return { copyPath: copyPath, stockPath: stockPath, dataPath: dataPath };
|
||||
}
|
||||
|
||||
type OrdinaryPhase = 'starting-server' | 'starting-game' | 'running' | 'server-running';
|
||||
|
||||
export async function runOrdinaryLaunch(
|
||||
copyPath: string, dataPath: string, port: number, settings: Settings, signal: AbortSignal,
|
||||
publish: (phase: OrdinaryPhase) => void,
|
||||
): Promise<void> {
|
||||
if (!ORDINARY_LAUNCH_ENABLED) throw new AppError('launch_disabled');
|
||||
const args = parseLaunchArguments(settings.launchArguments);
|
||||
if (!args) throw new AppError('launch_game_failed');
|
||||
publish('starting-server');
|
||||
const server = await startLocalServer({ gameFolder: copyPath, dataFolder: dataPath, port }, signal);
|
||||
const stop = new AbortController();
|
||||
const runSignal = AbortSignal.any([signal, stop.signal]);
|
||||
const serverExited = server.exited.then(() => { throw new AppError('launch_server_exited'); });
|
||||
publish('starting-game');
|
||||
const game = runGameProcess(copyPath, args, runSignal, () => publish('running'));
|
||||
try {
|
||||
await Promise.race([game, serverExited]);
|
||||
runSignal.throwIfAborted();
|
||||
if (!settings.closeServerOnGameExit) {
|
||||
publish('server-running');
|
||||
if (!runSignal.aborted) await Promise.race([once(runSignal, 'abort'), serverExited]);
|
||||
}
|
||||
} finally {
|
||||
stop.abort();
|
||||
await game.catch(() => undefined);
|
||||
await server.close();
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,8 @@ import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protoco
|
||||
import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
|
||||
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
|
||||
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
|
||||
import { labStatusUrl, readInstalledLab } from '../launch/lab-handoff.ts';
|
||||
import { readInstalledLab } from '../launch/lab-handoff.ts';
|
||||
import { localServerReady } from '../launch/local-server.ts';
|
||||
import { forwardProcessOutput } from '../launch/process-output.ts';
|
||||
import { archivedBackup, backupList, captureSave, changeSaveFolder, readArchive, restoreDirectory, saveBackup, writeArchive, type SaveArchive } from './save-archive.ts';
|
||||
|
||||
@@ -267,12 +268,7 @@ async function write<T>(operation: () => Promise<T>): Promise<T> {
|
||||
async function labServerRunning(): Promise<boolean> {
|
||||
const lab = await readInstalledLab().catch(() => null);
|
||||
if (!lab) return false;
|
||||
try {
|
||||
const response = await fetch(labStatusUrl(lab.port), { signal: AbortSignal.timeout(600) });
|
||||
return response.ok && (await response.json() as { app?: string }).app === 'wto-server';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return localServerReady(lab.port);
|
||||
}
|
||||
|
||||
async function run(task: SaveTask): Promise<SaveResult> {
|
||||
|
||||
Reference in new issue
Block a user