Skip to content

Open-source Xbox-inspired desktop launcher for Xodus on Linux

TypeScript

Batch library metadata persistence without deferring durable writes

domsvoboda9fd1b5eb5d8b
diff --git a/src/main/index.ts b/src/main/index.ts
index d67ddb4..3e21eb9 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1514,12 +1514,18 @@ async function enrichLibraryCovers(): Promise<void> {
const missing = store.games.filter((game) => game.storeId && (!game.coverUrl || !game.heroUrl));
if (missing.length === 0) return;
const artwork = await catalog.artwork(missing.map((game) => game.storeId!), currentMarket());
- for (const game of missing) {
+ const requested = new Map(missing.map(game => [game.id, game.storeId]));
+ const updates: { id: string; patch: Partial<Game> }[] = [];
+ // Recheck the live entries after the fetch: games can be removed or changed
+ // while artwork is in flight, and existing art must not be replaced.
+ for (const game of store.games) {
+ if (!game.storeId || requested.get(game.id) !== game.storeId) continue;
const images = artwork.get(game.storeId!.toUpperCase());
- if (images) await store.patchGame(game.id, {
- coverUrl: images.coverUrl ?? game.coverUrl, heroUrl: images.heroUrl ?? game.heroUrl,
- });
+ if (images && ((!game.coverUrl && images.coverUrl) || (!game.heroUrl && images.heroUrl))) updates.push({ id: game.id, patch: {
+ coverUrl: game.coverUrl || images.coverUrl, heroUrl: game.heroUrl || images.heroUrl,
+ } });
}
+ await store.patchGames(updates);
}
async function loadDemoCovers(): Promise<void> {
@@ -2406,10 +2412,11 @@ app.whenReady().then(async () => {
app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) void createWindow(); });
return;
}
+ const inspectedGames: { id: string; patch: Partial<Game> }[] = [];
for (const game of [...store.games]) {
try {
const inspected = await inspectGameDirectory(game.path);
- await store.patchGame(game.id, {
+ inspectedGames.push({ id: game.id, patch: {
installState: inspected.installState,
installMessage: inspected.installMessage,
updateIncomplete: inspected.updateIncomplete,
@@ -2420,12 +2427,13 @@ app.whenReady().then(async () => {
storeId: inspected.storeId ?? game.storeId,
installedVersion: inspected.installedVersion,
packageName: inspected.packageName,
- });
+ } });
} catch {
await refreshIncompleteUpdate(game).catch(() => {});
// Keep unavailable entries visible, without clearing any update barrier.
}
}
+ await store.patchGames(inspectedGames);
runtime = new RuntimeManager(store.settings.runtimeRoot, emitLog, () => downloadCancellations.size > 0 || operations.size > 0 || installQueue.size > 0 || preparingInstall || backend?.current.updating === true);
backend = new BackendManager(app.getPath('userData'), store.settings.externalXodusRoot, emitLog, () => keyringSupport.busy || downloadCancellations.size > 0 || operations.size > 0 || installQueue.size > 0 || preparingInstall || runtime?.current.updating === true);
await backend.refresh();
diff --git a/src/main/store-batch.test.ts b/src/main/store-batch.test.ts
new file mode 100644
index 0000000..ca9eb4a
--- /dev/null
+++ b/src/main/store-batch.test.ts
@@ -0,0 +1,81 @@
+import { promises as fs } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { afterEach, expect, it, vi } from 'vitest';
+import { StateStore } from './store.js';
+
+const directories: string[] = [];
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await Promise.all(directories.splice(0).map(dir => fs.rm(dir, { recursive: true, force: true })));
+});
+
+async function library(count = 2) {
+ const directory = await fs.mkdtemp(path.join(tmpdir(), 'nexus-batch-'));
+ directories.push(directory);
+ const file = path.join(directory, 'launcher-state.json');
+ await fs.writeFile(file, JSON.stringify({ games: Array.from({ length: count }, (_, i) => ({
+ id: String(i), title: `Game ${i}`, path: `/synthetic/${i}`, installState: 'ready',
+ addedAt: '2026-01-01T00:00:00Z', coverDataUrl: 'x'.repeat(32768),
+ })) }));
+ const store = new StateStore(directory);
+ await store.load();
+ return { store, file, directory };
+}
+
+it('persists a hundred metadata changes with one full-state write', async () => {
+ const { store, directory } = await library(100);
+ const writes = vi.spyOn(fs, 'writeFile');
+ const renames = vi.spyOn(fs, 'rename');
+ await store.patchGames(store.games.map(game => ({ id: game.id, patch: { publisher: `Publisher ${game.id}` } })));
+ expect(writes).toHaveBeenCalledTimes(1);
+ expect(renames).toHaveBeenCalledTimes(1);
+ expect(Buffer.byteLength(String(writes.mock.calls[0][1]))).toBeLessThan(3_400_000);
+ const reopened = new StateStore(directory);
+ await reopened.load();
+ expect(reopened.games).toHaveLength(100);
+ for (const game of reopened.games) expect(game.publisher).toBe(`Publisher ${game.id}`);
+});
+
+it('rejects an invalid batch before changing any entry or the saved state', async () => {
+ const { store, file } = await library();
+ const before = await fs.readFile(file, 'utf8');
+ const writes = vi.spyOn(fs, 'writeFile');
+ await expect(store.patchGames([
+ { id: '0', patch: { publisher: 'changed' } }, { id: 'removed', patch: { publisher: 'missing' } },
+ ])).rejects.toThrow('Game not found');
+ expect(store.games[0].publisher).toBeUndefined();
+ expect(writes).not.toHaveBeenCalled();
+ expect(await fs.readFile(file, 'utf8')).toBe(before);
+});
+
+it.each(['writeFile', 'rename'] as const)('propagates %s failure and retries identical metadata without discarding the old file', async operation => {
+ const { store, file, directory } = await library();
+ const before = await fs.readFile(file, 'utf8');
+ const fault = vi.spyOn(fs, operation).mockRejectedValueOnce(Object.assign(new Error('disk fault'), { code: 'EIO' }));
+ const batch = [{ id: '0', patch: { publisher: 'updated' } }];
+ await expect(store.patchGames(batch)).rejects.toThrow('disk fault');
+ expect(await fs.readFile(file, 'utf8')).toBe(before);
+ await store.patchGames(batch);
+ expect(fault).toHaveBeenCalledTimes(2);
+ const reopened = new StateStore(directory);
+ await reopened.load();
+ expect(reopened.games[0].publisher).toBe('updated');
+});
+
+it('keeps ordered writes with settings and makes an empty batch a no-op', async () => {
+ const { store, directory } = await library();
+ const writes = vi.spyOn(fs, 'writeFile');
+ await store.patchGames([]);
+ expect(writes).not.toHaveBeenCalled();
+ await Promise.all([
+ store.patchGames([{ id: '0', patch: { publisher: 'updated' } }]),
+ store.setSettings({ closeToTray: true }),
+ store.patchGame('1', { publisher: 'individual' }),
+ ]);
+ expect(writes).toHaveBeenCalledTimes(3);
+ const reopened = new StateStore(directory);
+ await reopened.load();
+ expect(reopened.settings.closeToTray).toBe(true);
+ expect(reopened.games.map(game => game.publisher)).toEqual(['updated', 'individual']);
+});
diff --git a/src/main/store.ts b/src/main/store.ts
index d9b444f..2a03155 100644
--- a/src/main/store.ts
+++ b/src/main/store.ts
@@ -113,6 +113,21 @@ export class StateStore {
return game;
}
+ async patchGames(updates: readonly { id: string; patch: Partial<Game> }[]): Promise<void> {
+ if (!updates.length) return;
+ const games = new Map(this.state.games.map(game => [game.id, game]));
+ // Validate the complete batch before changing any in-memory entry.
+ const targets = updates.map(update => {
+ const game = games.get(update.id);
+ if (!game) throw new Error('Game not found.');
+ return { game, patch: update.patch };
+ });
+ for (const { game, patch } of targets) Object.assign(game, patch);
+ // Keep the same awaited durability/error semantics as patchGame, including
+ // retry after a failed write even if the in-memory values already match.
+ await this.save();
+ }
+
async removeGame(id: string): Promise<void> {
this.state.games = this.state.games.filter((entry) => entry.id !== id);
await this.save();