Skip to content

Commit

Permalink
fix(core): change mkdir logic to avoid race condition
Browse files Browse the repository at this point in the history
The process of checking for directory existence then creating
A directory was causing race conditions when running scripts
In parallel. I inverted the logic to always try to
Create the directory without checking 1st, then handle any errors.
  • Loading branch information
jeffbcross authored and vsavkin committed Feb 26, 2020
1 parent 8e83fbb commit 7cb949d
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions packages/workspace/src/core/project-graph/project-graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,26 @@ interface ProjectGraphCache {
fileMap: FileMap;
}

const nxDepsPath = `${appRootPath}/dist/nxdeps.json`;
const distPath = `${appRootPath}/dist`;
const nxDepsPath = `${distPath}/nxdeps.json`;

function readCache(): false | { data: ProjectGraphCache; mtime: number } {
if (!directoryExists(`${appRootPath}/dist`)) {
mkdirSync(`${appRootPath}/dist`);
try {
mkdirSync(distPath);
} catch (e) {
/*
* @jeffbcross: Node JS docs recommend against checking for existence of directory immediately before creating it.
* Instead, just try to create the directory and handle the error.
*
* We ran into race conditions when running scripts concurrently, where multiple scripts were
* arriving here simultaneously, checking for directory existence, then trying to create the directory simultaneously.
*
* In this case, we're creating the directory. If the operation failed, we ensure that the directory
* exists before continuing (or raise an exception).
*/
if (!directoryExists(distPath)) {
throw new Error(`Failed to create directory: ${distPath}`);
}
}

const data = getValidCache(
Expand Down

0 comments on commit 7cb949d

Please sign in to comment.