diff --git a/lib/config-store.js b/lib/config-store.js index 6c7e58d..cc48375 100644 --- a/lib/config-store.js +++ b/lib/config-store.js @@ -4,6 +4,9 @@ const secretStore = require('./secret-store'); const { normalizeLogMode } = require('./log-mode'); const { mergeAutomationCompletions, normalizeAutomationCompletion, removeAutomationCompletions } = require('./automation-control'); +const TRANSIENT_RENAME_ERROR_CODES = new Set(['EPERM', 'EBUSY', 'EACCES']); +const RENAME_RETRY_DELAYS_MS = [50, 100, 200, 400, 800, 1600, 3200]; + const HOSTER_SETTINGS_DEFAULTS = { retries: 3, maxSpeedKbs: 0, // 0 = unlimited @@ -252,14 +255,23 @@ class ConfigStore { fs.renameSync(tmp, this.historyPath); } - _writeHistoryFileAtomic(arr) { - return new Promise((resolve, reject) => { - const tmp = this.historyPath + '.tmp'; - fs.writeFile(tmp, JSON.stringify(arr), 'utf-8', (err) => { - if (err) return reject(err); - fs.rename(tmp, this.historyPath, error => error ? reject(error) : resolve()); - }); - }); + async _writeHistoryFileAtomic(arr) { + const tmp = this.historyPath + '.tmp'; + await fs.promises.writeFile(tmp, JSON.stringify(arr), 'utf-8'); + await this._renameWithRetry(tmp, this.historyPath); + } + + async _renameWithRetry(from, to) { + const delays = this._renameRetryDelays || RENAME_RETRY_DELAYS_MS; + for (let attempt = 0; ; attempt += 1) { + try { + await fs.promises.rename(from, to); + return; + } catch (error) { + if (!TRANSIENT_RENAME_ERROR_CODES.has(error && error.code) || attempt >= delays.length) throw error; + await new Promise(resolve => setTimeout(resolve, delays[attempt])); + } + } } _quiescedWriteError() { @@ -715,7 +727,7 @@ class ConfigStore { } finally { await handle.close(); } - await fs.promises.rename(temporary, target); + await this._renameWithRetry(temporary, target); } _enqueueAutomationCompletionWrite(operation) { @@ -855,7 +867,7 @@ class ConfigStore { const current = await fs.promises.readFile(this.filePath, 'utf-8'); if (current && current.trim().length > 2) await fs.promises.writeFile(backupPath, current, 'utf-8'); } catch {} - await fs.promises.rename(tmpPath, this.filePath); + await this._renameWithRetry(tmpPath, this.filePath); this._cache = nextCache; this._cacheKey = ''; this._lastConfigCheck = Date.now();