From 72eb4f6f5dd565dfd86f56a8774665f669f79a4d Mon Sep 17 00:00:00 2001 From: Maximilian Antoni Date: Fri, 2 Aug 2024 07:51:46 +0200 Subject: [PATCH] Resolve timing issue with reading config --- lib/config.js | 7 ++++++- lib/config.test.js | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/lib/config.js b/lib/config.js index 8ebe5fd..0e1528d 100644 --- a/lib/config.js +++ b/lib/config.js @@ -17,8 +17,13 @@ import fs from 'node:fs/promises'; * @returns {Promise} */ export async function loadConfig(resolver) { + const filename = configFile(resolver); try { - const raw = await fs.readFile(configFile(resolver), 'utf8'); + let raw = await fs.readFile(filename, 'utf8'); + if (!raw) { + await new Promise((resolve) => setTimeout(resolve, 50)); + raw = await fs.readFile(filename, 'utf8'); + } const [token, port, pid, hash] = raw.split(' '); return { token, port: Number(port), pid: Number(pid), hash }; } catch { diff --git a/lib/config.test.js b/lib/config.test.js index 0873752..0854014 100644 --- a/lib/config.test.js +++ b/lib/config.test.js @@ -39,6 +39,29 @@ describe('lib/config', () => { await assert.resolves(promise, null); }); + + it('retries reading the file if content was empty', async () => { + const clock = sinon.useFakeTimers(); + const contents = ['', 'token 123 456 hash']; + sinon.replace( + fs, + 'readFile', + sinon.fake(() => Promise.resolve(contents.shift())) + ); + + const promise = loadConfig(resolver); + await Promise.resolve(); + assert.calledOnce(fs.readFile); + clock.tick(50); + + await assert.resolves(promise, { + token: 'token', + port: 123, + pid: 456, + hash: 'hash' + }); + assert.calledTwice(fs.readFile); + }); }); context('writeConfig', () => {