Skip to content

Commit 830939c

Browse files
committed
fix: Race condition on downloading the same file twice
1 parent 190b70f commit 830939c

File tree

2 files changed

+17
-8
lines changed

2 files changed

+17
-8
lines changed

test/data-options.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ it("noCopy test_fragment_multiframe", async () => {
169169
"https://github.com/dcmjs-org/data/releases/download/encapsulation/encapsulation-fragment-multiframe.dcm";
170170
const dcmPath = await getTestDataset(
171171
url,
172-
"encapsulation-fragment-multiframe-b.dcm"
172+
"encapsulation-fragment-multiframe.dcm"
173173
);
174174
const file = fs.readFileSync(dcmPath);
175175

test/testUtils.js

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -55,22 +55,31 @@ function ensureTestDataDir() {
5555
}
5656

5757
async function getZippedTestDataset(url, filename, unpackDirectory) {
58-
var dir = ensureTestDataDir();
59-
var targetPath = path.join(dir, filename);
60-
var unpackPath = path.join(dir, unpackDirectory);
58+
const dir = ensureTestDataDir();
59+
const targetPath = path.join(dir, filename);
60+
const unpackPath = path.join(dir, unpackDirectory);
6161
if (!fs.existsSync(unpackPath)) {
6262
await downloadToFile(url, targetPath);
6363
await unzip(targetPath, unpackPath);
6464
}
6565
return unpackPath;
6666
}
6767

68+
/**
69+
* Stores the required downloads to prevent async reading before download completed.
70+
*/
71+
const asyncDownloadMap = new Map();
72+
6873
async function getTestDataset(url, filename) {
69-
var dir = ensureTestDataDir();
70-
var targetPath = path.join(dir, filename);
71-
if (!fs.existsSync(targetPath)) {
72-
await downloadToFile(url, targetPath);
74+
const dir = ensureTestDataDir();
75+
const targetPath = path.join(dir, filename);
76+
let filePromise = asyncDownloadMap.get(targetPath);
77+
if (!filePromise && !fs.existsSync(targetPath)) {
78+
filePromise = downloadToFile(url, targetPath);
79+
asyncDownloadMap.set(targetPath,filePromise);
7380
}
81+
// This returns immediately if filePromise is undefined - eg if the file already downloaded.
82+
await filePromise;
7483
return targetPath;
7584
}
7685

0 commit comments

Comments
 (0)