1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | Object.defineProperty(exports, "__esModule", { value: true });
|
7 | const fs = require("fs");
|
8 | const promisify = require("pify");
|
9 | const tasks_1 = require("@microsoft.azure/tasks");
|
10 | const file_io_1 = require("./file-io");
|
11 | const { lock, check, } = require("proper-lockfile");
|
12 | const fs_open = promisify(fs.open);
|
13 | class UnableToReadLockException extends tasks_1.Exception {
|
14 | constructor(path, exitCode = 1) {
|
15 | super(`Unable to create read lock on '${path}'.`, exitCode);
|
16 | this.exitCode = exitCode;
|
17 | Object.setPrototypeOf(this, UnableToReadLockException.prototype);
|
18 | }
|
19 | }
|
20 | exports.UnableToReadLockException = UnableToReadLockException;
|
21 | class Lock {
|
22 | static async exclusive(path, options) {
|
23 | return promisify(await this._exclusive(path, options));
|
24 | }
|
25 | static async waitForExclusive(path, timeout = 5 * 60 * 1000) {
|
26 | let result = null;
|
27 | const expire = Date.now() + timeout;
|
28 | do {
|
29 | try {
|
30 | result = await this.exclusive(path);
|
31 | }
|
32 | catch (e) {
|
33 |
|
34 | await tasks_1.Delay(3000);
|
35 | }
|
36 | } while (result == null && expire > Date.now());
|
37 | return result;
|
38 | }
|
39 | static async read(path, options) {
|
40 |
|
41 |
|
42 | options = options || {};
|
43 | options.delay = options.delay || 2000;
|
44 | options.retries = options.retries || 4;
|
45 | const p = `${path}.lock`;
|
46 | try {
|
47 | fs.writeFileSync(p, 'lockfile');
|
48 | }
|
49 | catch (e) {
|
50 |
|
51 | }
|
52 |
|
53 | try {
|
54 | if (await file_io_1.isFile(p)) {
|
55 | const fd = await fs_open(p, 'r');
|
56 | return async () => {
|
57 | fs.close(fd, (err) => { });
|
58 | try {
|
59 | fs.unlinkSync(p);
|
60 | }
|
61 | catch (E) {
|
62 | }
|
63 | };
|
64 | }
|
65 | }
|
66 | catch (e) {
|
67 | }
|
68 | if (options.retries) {
|
69 | await tasks_1.Delay(options.delay);
|
70 | options.retries--;
|
71 | return await this.read(p, options);
|
72 | }
|
73 | throw new UnableToReadLockException(path);
|
74 | }
|
75 | }
|
76 | Lock._exclusive = promisify(lock);
|
77 | Lock.check = promisify(check);
|
78 | exports.Lock = Lock;
|
79 |
|
\ | No newline at end of file |