| 13 | * that the file is still 'held' by someone. |
| 14 | */ |
| 15 | export class LeaseFile implements IDisposable { |
| 16 | private static readonly updateInterval = 1000; |
| 17 | private static readonly recencyDeadline = 2000; |
| 18 | private file: Promise<fs.FileHandle>; |
| 19 | private disposed = false; |
| 20 | |
| 21 | /** |
| 22 | * Path of the callback file. |
| 23 | */ |
| 24 | public readonly path = path.join( |
| 25 | tmpdir(), |
| 26 | `node-debug-callback-${randomBytes(8).toString('hex')}`, |
| 27 | ); |
| 28 | |
| 29 | /** |
| 30 | * Update timer. |
| 31 | */ |
| 32 | private updateInterval?: NodeJS.Timeout; |
| 33 | |
| 34 | constructor() { |
| 35 | this.file = fs.open(this.path, 'w'); |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Returns whether the given file path points to a valid lease. |
| 40 | */ |
| 41 | public static isValid(file: string) { |
| 42 | try { |
| 43 | const contents = readFileSync(file); |
| 44 | if (!contents.length) { |
| 45 | return false; |
| 46 | } |
| 47 | |
| 48 | return contents.readDoubleBE() > Date.now() - LeaseFile.recencyDeadline; |
| 49 | } catch { |
| 50 | return false; |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Starts keeping the file up to date. |
| 56 | */ |
| 57 | public async startTouchLoop() { |
| 58 | await this.touch(); |
| 59 | if (!this.disposed) { |
| 60 | this.updateInterval = setInterval(() => this.touch(), LeaseFile.updateInterval); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * Updates the leased file. |
| 66 | */ |
| 67 | public async touch(dateProvider = () => Date.now()) { |
| 68 | const fd = await this.file; |
| 69 | const buf = Buffer.alloc(8); |
| 70 | buf.writeDoubleBE(dateProvider()); |
| 71 | await fd.write(buf, 0, buf.length, 0); |
| 72 | } |