UNPKG

2.83 kBJavaScriptView Raw
1"use strict";
2/*---------------------------------------------------------------------------------------------
3 * Copyright (c) Microsoft Corporation. All rights reserved.
4 * Licensed under the MIT License. See License.txt in the project root for license information.
5 *--------------------------------------------------------------------------------------------*/
6Object.defineProperty(exports, "__esModule", { value: true });
7const fs = require("fs");
8const promisify = require("pify");
9const tasks_1 = require("@microsoft.azure/tasks");
10const file_io_1 = require("./file-io");
11const { lock, check, } = require("proper-lockfile");
12const fs_open = promisify(fs.open);
13class 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}
20exports.UnableToReadLockException = UnableToReadLockException;
21class 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 // no worries. Just wait a few seconds and see if we can get it.
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 // first try to create the file
41 // it's ok if it fails
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 // no worries.
51 }
52 // try to open the file for read
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}
76Lock._exclusive = promisify(lock);
77Lock.check = promisify(check);
78exports.Lock = Lock;
79//# sourceMappingURL=lock.js.map
\No newline at end of file