-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lockfile.ts
100 lines (100 loc) · 3.13 KB
/
Lockfile.ts
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* Copyright (c) 2018-present, heineiuo.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { Options } from "./Options.ts";
interface Timer {
hasRef(): boolean;
ref(): this;
refresh(): this;
unref(): this;
}
export class Lockfile {
constructor(filename: string, options: Options) {
this.filename = filename;
this.options = options;
this.filetime = options.env.platform() === "win32" ? "mtime" : "ctime";
this.stale = options.lockfileStale;
this.options.env.onExit(() => {
// if db has been destoryed manully, unlink will fail.
try {
this.options.env.unlinkSync(this.filename);
}
catch (e) { }
});
}
private filetime: "mtime" | "ctime";
private filename: string;
private options: Options;
private refreshLockTimer!: Timer;
private _locked = false;
private stale: number;
public get locked(): boolean {
return this._locked;
}
public async unlock(): Promise<void> {
try {
// if db has been destoryed manully, unlink will fail.
await this.options.env.unlink(this.filename);
}
catch (e) { }
this._locked = false;
clearInterval(this.refreshLockTimer);
}
private async waitUntilExpire(startTime = Date.now()): Promise<boolean> {
try {
const fd = await this.options.env.open(this.filename, "r");
try {
const stats = await fd.stat();
const filetime = new Date(stats[this.filetime]).getTime();
if (Date.now() > filetime + this.stale + 1000)
return true;
}
catch (e) {
}
finally {
await fd.close();
}
// wait time should be longer
if (Date.now() > startTime + this.stale * 2 + 1000)
return false;
await new Promise((resolve) => setTimeout(resolve, this.stale / 2));
return await this.waitUntilExpire(startTime);
}
catch (e) {
return false;
}
}
private async waitUntilOk(): Promise<boolean> {
try {
const fd = await this.options.env.open(this.filename, "r");
await fd.close();
// file exist, wait file expire
const expired = await this.waitUntilExpire();
return expired;
}
catch (e) {
if (e.code === "ENOENT") {
return true;
}
return false;
}
}
public async writeSomething(): Promise<void> {
try {
await this.options.env.writeFile(this.filename, ``);
this._locked = true;
}
catch (e) { }
}
public async lock(): Promise<void> {
const ok = await this.waitUntilOk();
if (!ok) {
throw new Error("Lock fail");
}
await this.writeSomething();
this.refreshLockTimer = setInterval(() => this.writeSomething(), this.stale / 2);
}
}