A local-first personal finance app
[AI] Fix desktop settings resetting after an interrupted update (#8101)
Matiss Janis Aboltinsffae169cbb1c
diff --git a/packages/loot-core/src/platform/server/asyncStorage/index.electron.test.ts b/packages/loot-core/src/platform/server/asyncStorage/index.electron.test.tsnew file mode 100644index 0000000000..df80aed00f--- /dev/null+++ b/packages/loot-core/src/platform/server/asyncStorage/index.electron.test.ts@@ -0,0 +1,112 @@+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';++import * as asyncStorage from '#platform/server/asyncStorage';++// Under the test config `#platform/server/asyncStorage` resolves to the+// electron implementation, but it is globally mocked with an in-memory store in+// the test setup. Undo that so we exercise the real on-disk persistence logic.+vi.unmock('#platform/server/asyncStorage');++let dataDir: string;+const storePath = () => path.join(dataDir, 'global-store.json');++beforeEach(() => {+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'actual-global-store-'));+ process.env.ACTUAL_DATA_DIR = dataDir;+});++afterEach(() => {+ fs.rmSync(dataDir, { recursive: true, force: true });+ delete process.env.ACTUAL_DATA_DIR;+});++describe('electron asyncStorage', () => {+ it('persists values as valid JSON and reads them back', async () => {+ asyncStorage.init();+ await asyncStorage.setItem('language', 'en');++ // The on-disk file is complete, valid JSON.+ const raw = fs.readFileSync(storePath(), 'utf8');+ expect(JSON.parse(raw)).toEqual({ language: 'en' });++ // A fresh init reads the persisted value.+ asyncStorage.init();+ expect(await asyncStorage.getItem('language')).toBe('en');+ });++ it('does not leave temp files behind after a write', async () => {+ asyncStorage.init();+ await asyncStorage.setItem('language', 'en');+ await asyncStorage.setItem('theme', 'dark');++ const leftovers = fs+ .readdirSync(dataDir)+ .filter(name => name.endsWith('.tmp'));+ expect(leftovers).toEqual([]);+ });++ it('keeps the store valid under concurrent writes', async () => {+ asyncStorage.init();++ await Promise.all([+ asyncStorage.setItem('language', 'en'),+ asyncStorage.setItem('theme', 'dark'),+ asyncStorage.multiSet([+ ['max-months', '3'],+ ['floating-sidebar', 'true'],+ ]),+ ]);++ // The file is complete, valid JSON, retains every key (no write clobbered+ // another), and leaves no temp files behind.+ expect(JSON.parse(fs.readFileSync(storePath(), 'utf8'))).toEqual({+ language: 'en',+ theme: 'dark',+ 'max-months': '3',+ 'floating-sidebar': 'true',+ });+ expect(+ fs.readdirSync(dataDir).filter(name => name.endsWith('.tmp')),+ ).toEqual([]);+ });++ it('starts empty without a backup when no store file exists', () => {+ asyncStorage.init();++ expect(fs.existsSync(storePath())).toBe(false);+ expect(fs.existsSync(`${storePath()}.corrupt`)).toBe(false);+ });++ it('backs up a corrupt store instead of silently wiping it', async () => {+ // Simulate a truncated/corrupt file left behind by an interrupted write+ // (e.g. the process was killed mid-write during an app update).+ const corrupt = '{"language":"en"';+ fs.writeFileSync(storePath(), corrupt, 'utf8');++ // init must not throw, and must start from defaults.+ expect(() => asyncStorage.init()).not.toThrow();+ expect(await asyncStorage.getItem('language')).toBeUndefined();++ // The corrupt content is preserved in a backup so it can be recovered,+ // rather than being thrown away.+ const backupPath = `${storePath()}.corrupt`;+ expect(fs.existsSync(backupPath)).toBe(true);+ expect(fs.readFileSync(backupPath, 'utf8')).toBe(corrupt);+ });++ it('backs up valid JSON of the wrong shape instead of using it as the store', async () => {+ // Parseable JSON, but not a plain object (e.g. `null` or an array) would+ // break `store[key]` access if used directly.+ const invalid = '[]';+ fs.writeFileSync(storePath(), invalid, 'utf8');++ expect(() => asyncStorage.init()).not.toThrow();+ expect(await asyncStorage.getItem('language')).toBeUndefined();++ const backupPath = `${storePath()}.corrupt`;+ expect(fs.existsSync(backupPath)).toBe(true);+ expect(fs.readFileSync(backupPath, 'utf8')).toBe(invalid);+ });+});diff --git a/packages/loot-core/src/platform/server/asyncStorage/index.electron.ts b/packages/loot-core/src/platform/server/asyncStorage/index.electron.tsindex abca071ad7..d8ce8322dd 100644--- a/packages/loot-core/src/platform/server/asyncStorage/index.electron.ts+++ b/packages/loot-core/src/platform/server/asyncStorage/index.electron.ts@@ -3,6 +3,7 @@ import * as fs from 'fs';import { join } from 'path';import * as lootFs from '#platform/server/fs';+import { logger } from '#platform/server/log';import type { GlobalPrefsJson } from '#types/prefs';import type * as T from './index-types';@@ -11,13 +12,17 @@ const getStorePath = () => join(lootFs.getDataDir(), 'global-store.json');let store: GlobalPrefsJson;let persisted = true;+// Gives each write a unique temp file so concurrent writes never interleave+// into the same file before being atomically renamed into place.+let writeCounter = 0;++// Serializes disk writes. Without this, two in-flight writes could finish out+// of order and let an older snapshot clobber a newer one on disk.+let pendingSave: Promise<void> = Promise.resolve();+export const init: T.Init = function ({ persist = true } = {}) {if (persist) {- try {- store = JSON.parse(fs.readFileSync(getStorePath(), 'utf8'));- } catch {- store = {};- }+ store = loadStore(getStorePath());} else {store = {};}@@ -25,18 +30,83 @@ export const init: T.Init = function ({ persist = true } = {}) {persisted = persist;};-function _saveStore(): Promise<void> {- if (persisted) {- return new Promise(function (resolve, reject) {- fs.writeFile(- getStorePath(),- JSON.stringify(store),- 'utf8',- function (err) {- return err ? reject(err) : resolve();- },+function loadStore(storePath: string): GlobalPrefsJson {+ let contents: string;+ try {+ contents = fs.readFileSync(storePath, 'utf8');+ } catch (err) {+ // No store yet (first run) - start fresh. Anything other than a missing+ // file is unexpected, so surface it but still fall back to defaults.+ if (err?.code !== 'ENOENT') {+ logger.error('Could not read global preferences, using defaults', err);+ }+ return {};+ }++ try {+ const parsed = JSON.parse(contents);+ if (+ parsed === null ||+ typeof parsed !== 'object' ||+ Array.isArray(parsed)+ ) {+ throw new Error('Global preferences are not a JSON object');+ }+ return parsed;+ } catch (err) {+ // The file exists but isn't a usable preferences object - either invalid+ // JSON (most likely truncated by an interrupted write, e.g. the process was+ // killed mid-write during an app update) or valid JSON of the wrong shape.+ // Don't silently discard the user's preferences: back the file up so it can+ // be recovered, and log loudly.+ const backupPath = `${storePath}.corrupt`;+ try {+ fs.writeFileSync(backupPath, contents, 'utf8');+ logger.error(+ `Could not parse global preferences at ${storePath}; backed up the corrupt file to ${backupPath} and started with defaults`,+ err,+ );+ } catch (backupErr) {+ logger.error(+ `Could not parse global preferences at ${storePath}, and failed to back up the corrupt file; starting with defaults`,+ backupErr,);- });+ }+ return {};+ }+}++function _saveStore(): Promise<void> {+ if (!persisted) {+ return Promise.resolve();+ }++ // Queue this write behind any in-flight one. Using `writeStore` for both+ // outcomes means a failed write doesn't permanently block the queue. Each+ // queued write snapshots the latest store when it actually runs, so the file+ // always ends up reflecting the most recent state.+ pendingSave = pendingSave.then(writeStore, writeStore);+ return pendingSave;+}++async function writeStore(): Promise<void> {+ const storePath = getStorePath();+ // Write to a unique temp file and atomically rename it into place. This+ // guarantees the store file is always either the old or the new complete+ // contents - never a half-written file - even if the process is killed+ // mid-write (such as during an app update).+ const tmpPath = `${storePath}.${process.pid}.${writeCounter++}.tmp`;++ try {+ await fs.promises.writeFile(tmpPath, JSON.stringify(store), 'utf8');+ await fs.promises.rename(tmpPath, storePath);+ } catch (err) {+ // Best-effort cleanup of the temp file; ignore failures (it may never have+ // been created).+ try {+ await fs.promises.rm(tmpPath, { force: true });+ } catch {}+ throw err;}}diff --git a/upcoming-release-notes/fix-global-prefs-reset-on-update.md b/upcoming-release-notes/fix-global-prefs-reset-on-update.mdnew file mode 100644index 0000000000..6e6e3270c2--- /dev/null+++ b/upcoming-release-notes/fix-global-prefs-reset-on-update.md@@ -0,0 +1,6 @@+---+category: Bugfixes+authors: [MatissJanis]+---++Fixed desktop settings (such as the selected language) being reset to defaults after an interrupted app update.