Skip to content

Commit

Permalink
Resolve timing issue with reading config
Browse files Browse the repository at this point in the history
mantoni committed Aug 2, 2024
1 parent e24151d commit 72eb4f6
Showing 2 changed files with 29 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/config.js
Original file line number Diff line number Diff line change
@@ -17,8 +17,13 @@ import fs from 'node:fs/promises';
* @returns {Promise<Config | null>}
*/
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 {
23 changes: 23 additions & 0 deletions lib/config.test.js
Original file line number Diff line number Diff line change
@@ -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', () => {

0 comments on commit 72eb4f6

Please sign in to comment.