( updater: (current: Settings) => Settings | Promise<Settings> )
| 47 | * Atomically update settings with file locking |
| 48 | */ |
| 49 | export async function updateSettings( |
| 50 | updater: (current: Settings) => Settings | Promise<Settings> |
| 51 | ): Promise<Settings> { |
| 52 | const LOCK_RETRY_INTERVAL_MS = 100; |
| 53 | const MAX_LOCK_ATTEMPTS = 50; |
| 54 | const STALE_LOCK_TIMEOUT_MS = 10000; |
| 55 | |
| 56 | const lockFile = configuration.settingsFile + '.lock'; |
| 57 | const tmpFile = configuration.settingsFile + '.tmp'; |
| 58 | let fileHandle; |
| 59 | let attempts = 0; |
| 60 | |
| 61 | while (attempts < MAX_LOCK_ATTEMPTS) { |
| 62 | try { |
| 63 | fileHandle = await open(lockFile, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY); |
| 64 | break; |
| 65 | } catch (err: any) { |
| 66 | if (err.code === 'EEXIST') { |
| 67 | attempts++; |
| 68 | await new Promise(resolve => setTimeout(resolve, LOCK_RETRY_INTERVAL_MS)); |
| 69 | try { |
| 70 | const stats = await stat(lockFile); |
| 71 | if (Date.now() - stats.mtimeMs > STALE_LOCK_TIMEOUT_MS) { |
| 72 | await unlink(lockFile).catch(() => { }); |
| 73 | } |
| 74 | } catch { } |
| 75 | } else { |
| 76 | throw err; |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | if (!fileHandle) { |
| 82 | throw new Error(`Failed to acquire settings lock after ${MAX_LOCK_ATTEMPTS * LOCK_RETRY_INTERVAL_MS / 1000} seconds`); |
| 83 | } |
| 84 | |
| 85 | try { |
| 86 | const current = await readSettings() || { ...defaultSettings }; |
| 87 | const updated = await updater(current); |
| 88 | if (!existsSync(configuration.consortiumHomeDir)) { |
| 89 | await mkdir(configuration.consortiumHomeDir, { recursive: true }); |
| 90 | } |
| 91 | await writeFile(tmpFile, JSON.stringify(updated, null, 2)); |
| 92 | await rename(tmpFile, configuration.settingsFile); |
| 93 | return updated; |
| 94 | } finally { |
| 95 | await fileHandle.close(); |
| 96 | await unlink(lockFile).catch(() => { }); |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | // |
| 101 | // Authentication |
no test coverage detected