-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(core): lock graph creation when running in another process
- Loading branch information
1 parent
a675bd2
commit c66f06a
Showing
2 changed files
with
88 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
import { existsSync, rmSync, watch, writeFileSync } from 'fs'; | ||
|
||
export class FileLock { | ||
locked: boolean; | ||
|
||
private lockFilePath: string; | ||
lockPromise: Promise<void>; | ||
|
||
constructor(private file: string) { | ||
this.lockFilePath = `${file}.lock`; | ||
this.locked = existsSync(this.lockFilePath); | ||
} | ||
|
||
lock() { | ||
if (this.locked) { | ||
throw new Error(`File ${this.lockFilePath} is already locked`); | ||
} | ||
this.locked = true; | ||
writeFileSync(this.file, ''); | ||
} | ||
|
||
unlock() { | ||
if (!this.locked) { | ||
throw new Error(`File ${this.lockFilePath} is not locked`); | ||
} | ||
this.locked = false; | ||
rmSync(this.file); | ||
} | ||
|
||
wait(timeout?: number) { | ||
return new Promise<void>((res, rej) => { | ||
try { | ||
let watcher = watch(this.lockFilePath); | ||
|
||
watcher.on('change', (eventType) => { | ||
if (eventType === 'delete') { | ||
this.locked = false; | ||
res(); | ||
watcher.close(); | ||
} | ||
}); | ||
} catch { | ||
// File watching is not supported | ||
let start = Date.now(); | ||
setInterval(() => { | ||
if (!this.locked || !existsSync(this.file)) { | ||
res(); | ||
} | ||
|
||
const elapsed = Date.now() - start; | ||
if (timeout && elapsed > timeout) { | ||
rej( | ||
new Error(`Timeout waiting for file lock ${this.lockFilePath}`) | ||
); | ||
} | ||
}, 2); | ||
} | ||
}); | ||
} | ||
} |