forked from testcontainers/testcontainers-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile-lock.ts
More file actions
38 lines (35 loc) · 1.13 KB
/
file-lock.ts
File metadata and controls
38 lines (35 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { writeFile } from "fs/promises";
import path from "path";
import lockFile from "proper-lockfile";
import { log } from "./logger";
export async function withFileLock<T>(fileName: string, fn: () => T): Promise<T> {
const file = await createEmptyTmpFile(fileName);
let releaseLockFn;
try {
log.debug(`Acquiring lock file "${file}"...`);
releaseLockFn = await lockFile.lock(file, {
retries: { forever: true, factor: 1, minTimeout: 500, maxTimeout: 3000, randomize: true },
});
log.debug(`Acquired lock file "${file}"`);
return await fn();
} finally {
if (releaseLockFn) {
log.debug(`Releasing lock file "${file}"...`);
await releaseLockFn();
log.debug(`Released lock file "${file}"`);
}
}
}
async function createEmptyTmpFile(fileName: string): Promise<string> {
const tmp = await import("tmp");
const file = path.resolve(tmp.tmpdir, fileName);
try {
await writeFile(file, "", { flag: "wx" });
} catch (err) {
const isExistError = err && typeof err === "object" && "code" in err && err.code === "EEXIST";
if (!isExistError) {
throw err;
}
}
return file;
}