better-lock 1.0.0 → 2.0.1-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/.eslintrc.js +24 -0
  2. package/.idea/better-lock.iml +1 -7
  3. package/.idea/codeStyles/Project.xml +336 -5
  4. package/.idea/compiler.xml +7 -0
  5. package/.idea/inspectionProfiles/Project_Default.xml +6 -2
  6. package/.idea/jsLibraryMappings.xml +0 -1
  7. package/.idea/modules.xml +1 -1
  8. package/.idea/prettier.xml +8 -0
  9. package/.prettierrc.yaml +1 -3
  10. package/.travis.yml +2 -2
  11. package/README.md +102 -53
  12. package/dist/better_lock.d.ts +50 -0
  13. package/dist/better_lock.js +317 -0
  14. package/dist/better_lock.js.map +1 -0
  15. package/dist/errors.d.ts +44 -0
  16. package/dist/errors.js +131 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/index.d.ts +16 -0
  19. package/dist/index.js +28 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/internals.d.ts +75 -0
  22. package/dist/internals.js +75 -0
  23. package/dist/internals.js.map +1 -0
  24. package/dist/options.d.ts +54 -0
  25. package/dist/options.js +3 -0
  26. package/dist/options.js.map +1 -0
  27. package/dist/tools.d.ts +19 -0
  28. package/dist/tools.js +109 -0
  29. package/dist/tools.js.map +1 -0
  30. package/dist/types.d.ts +23 -0
  31. package/dist/types.js +3 -0
  32. package/dist/types.js.map +1 -0
  33. package/jest.config.js +4 -0
  34. package/package.json +30 -8
  35. package/spec/better_lock.spec.ts +614 -0
  36. package/src/better_lock.ts +430 -0
  37. package/src/errors.ts +124 -0
  38. package/src/index.ts +54 -0
  39. package/src/internals.ts +118 -0
  40. package/src/options.ts +63 -0
  41. package/src/tools.ts +111 -0
  42. package/src/types.ts +29 -0
  43. package/tsconfig.json +13 -0
  44. package/.idea/markdown-navigator/profiles_settings.xml +0 -3
  45. package/.idea/markdown-navigator.xml +0 -78
  46. package/.idea/misc.xml +0 -6
  47. package/.idea/watcherTasks.xml +0 -8
  48. package/index.js +0 -19
  49. package/spec/better_lock.spec.js +0 -583
  50. package/src/better_lock.js +0 -400
  51. package/src/errors.js +0 -81
  52. package/src/options.js +0 -104
  53. package/src/tools.js +0 -125
  54. package/src/types.js +0 -110
package/dist/errors.js ADDED
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.BetterLockJobAbortedError = exports.BetterLockQueueOverflowError = exports.BetterLockExecutionTimeoutError = exports.BetterLockWaitTimeoutError = exports.BetterLockInvalidArgumentError = exports.BetterLockInternalError = exports.BetterLockError = void 0;
19
+ var internals_1 = require("./internals");
20
+ var BetterLockError = /** @class */ (function (_super) {
21
+ __extends(BetterLockError, _super);
22
+ function BetterLockError(lockName, message, incomingStack) {
23
+ var _newTarget = this.constructor;
24
+ if (incomingStack === void 0) { incomingStack = null; }
25
+ var _this = this;
26
+ // Fix typescript custom Error prototype chain
27
+ // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
28
+ // https://github.com/reduardo7/ts-base-error/blob/master/src/index.ts
29
+ var trueProto = _newTarget.prototype;
30
+ if (lockName) {
31
+ _this = _super.call(this, "[" + lockName + "] " + message) || this;
32
+ }
33
+ else {
34
+ _this = _super.call(this, message) || this;
35
+ }
36
+ Object.setPrototypeOf(_this, trueProto);
37
+ _this.lock_name = lockName;
38
+ _this.name = _this.constructor.name;
39
+ if (incomingStack) {
40
+ var withoutFirstLine = incomingStack.split('\n').slice(1).join('\n');
41
+ _this.stack =
42
+ _this.stack +
43
+ '\n --------------------------------------------------------------------------------\n' +
44
+ withoutFirstLine;
45
+ }
46
+ return _this;
47
+ }
48
+ return BetterLockError;
49
+ }(Error));
50
+ exports.BetterLockError = BetterLockError;
51
+ var BetterLockInternalError = /** @class */ (function (_super) {
52
+ __extends(BetterLockInternalError, _super);
53
+ function BetterLockInternalError(lockName, message) {
54
+ var _this = this;
55
+ var lastChar = message[message.length - 1];
56
+ if (lastChar !== '.' && lastChar !== '!' && lastChar !== '?') {
57
+ message += '.';
58
+ }
59
+ _this = _super.call(this, lockName, message + ' This is probably a bug inside "better-lock" library') || this;
60
+ return _this;
61
+ }
62
+ return BetterLockInternalError;
63
+ }(BetterLockError));
64
+ exports.BetterLockInternalError = BetterLockInternalError;
65
+ var BetterLockInvalidArgumentError = /** @class */ (function (_super) {
66
+ __extends(BetterLockInvalidArgumentError, _super);
67
+ function BetterLockInvalidArgumentError(lockName, argument, expected, actual) {
68
+ var _this = _super.call(this, lockName, "Argument \"" + argument + "\" must be " + expected + " (got: \"" + actual + "\")") || this;
69
+ _this.argument = argument;
70
+ _this.argument = argument;
71
+ return _this;
72
+ }
73
+ return BetterLockInvalidArgumentError;
74
+ }(BetterLockError));
75
+ exports.BetterLockInvalidArgumentError = BetterLockInvalidArgumentError;
76
+ var BetterLockWaitTimeoutError = /** @class */ (function (_super) {
77
+ __extends(BetterLockWaitTimeoutError, _super);
78
+ function BetterLockWaitTimeoutError(lockName, job) {
79
+ var _this = this;
80
+ var message = job + " has timed out after " + (new Date().valueOf() - job.enqueued_at.valueOf()) + "ms in wait queue";
81
+ _this = _super.call(this, lockName, message, job.incoming_stack) || this;
82
+ _this.job_id = job.id;
83
+ _this.keys = job.keys;
84
+ _this.enqueued_at = job.enqueued_at;
85
+ return _this;
86
+ }
87
+ return BetterLockWaitTimeoutError;
88
+ }(BetterLockError));
89
+ exports.BetterLockWaitTimeoutError = BetterLockWaitTimeoutError;
90
+ var BetterLockExecutionTimeoutError = /** @class */ (function (_super) {
91
+ __extends(BetterLockExecutionTimeoutError, _super);
92
+ function BetterLockExecutionTimeoutError(lockName, job) {
93
+ var _this = this;
94
+ var message = job + " has timed out after " + (new Date().valueOf() - job.executed_at.valueOf()) + "ms of execution";
95
+ _this = _super.call(this, lockName, message, job.incoming_stack) || this;
96
+ _this.job_id = job.id;
97
+ _this.keys = job.keys;
98
+ _this.executed_at = job.executed_at;
99
+ return _this;
100
+ }
101
+ return BetterLockExecutionTimeoutError;
102
+ }(BetterLockError));
103
+ exports.BetterLockExecutionTimeoutError = BetterLockExecutionTimeoutError;
104
+ var BetterLockQueueOverflowError = /** @class */ (function (_super) {
105
+ __extends(BetterLockQueueOverflowError, _super);
106
+ function BetterLockQueueOverflowError(lockName, key, count, job) {
107
+ var _this = this;
108
+ var keyDesignation = key === internals_1.KeyQueue.DEFAULT_QUEUE_KEY ? '' : " for key \"" + key + "\"";
109
+ var message = "Too many jobs (" + count + ") are waiting" + keyDesignation + ". The most recent job (" + job + ") was kicked out";
110
+ _this = _super.call(this, lockName, message, job.incoming_stack) || this;
111
+ _this.job_id = job.id;
112
+ _this.keys = job.keys;
113
+ _this.job_count = count;
114
+ _this.kicked_out_job_id = job.id;
115
+ return _this;
116
+ }
117
+ return BetterLockQueueOverflowError;
118
+ }(BetterLockError));
119
+ exports.BetterLockQueueOverflowError = BetterLockQueueOverflowError;
120
+ var BetterLockJobAbortedError = /** @class */ (function (_super) {
121
+ __extends(BetterLockJobAbortedError, _super);
122
+ function BetterLockJobAbortedError(lockName, job) {
123
+ var _this = _super.call(this, lockName, job + " has been aborted by the user", job.incoming_stack) || this;
124
+ _this.job_id = job.id;
125
+ _this.keys = job.keys;
126
+ return _this;
127
+ }
128
+ return BetterLockJobAbortedError;
129
+ }(BetterLockError));
130
+ exports.BetterLockJobAbortedError = BetterLockJobAbortedError;
131
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,yCAAgD;AAGhD;IAAqC,mCAAK;IAWxC,yBAAY,QAAQ,EAAE,OAAO,EAAE,aAAoB;;QAApB,8BAAA,EAAA,oBAAoB;QAAnD,iBAwBC;QAvBC,8CAA8C;QAC9C,gIAAgI;QAChI,sEAAsE;QACtE,IAAM,SAAS,GAAG,WAAW,SAAS,CAAC;QAEvC,IAAI,QAAQ,EAAE;YACZ,QAAA,kBAAM,MAAI,QAAQ,UAAK,OAAS,CAAC,SAAC;SACnC;aAAM;YACL,QAAA,kBAAM,OAAO,CAAC,SAAC;SAChB;QAED,MAAM,CAAC,cAAc,CAAC,KAAI,EAAE,SAAS,CAAC,CAAC;QAEvC,KAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,KAAI,CAAC,IAAI,GAAG,KAAI,CAAC,WAAW,CAAC,IAAkB,CAAC;QAEhD,IAAI,aAAa,EAAE;YACjB,IAAM,gBAAgB,GAAG,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACvE,KAAI,CAAC,KAAK;gBACR,KAAI,CAAC,KAAK;oBACV,0FAA0F;oBAC1F,gBAAgB,CAAC;SACpB;;IACH,CAAC;IACH,sBAAC;AAAD,CAAC,AApCD,CAAqC,KAAK,GAoCzC;AApCY,0CAAe;AAsC5B;IAA6C,2CAAe;IAC1D,iCAAY,QAAQ,EAAE,OAAO;QAA7B,iBAMC;QALC,IAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC7C,IAAI,QAAQ,KAAK,GA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,CAAC;QACrB,KAAI,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC;;IACvB,CAAC;IACH,gCAAC;AAAD,CAAC,AAVD,CAA+C,eAAe,GAU7D;AAVY,8DAAyB"}
@@ -0,0 +1,16 @@
1
+ import { BetterLock as BetterLockUnadorned } from './better_lock';
2
+ import { BetterLockError, BetterLockExecutionTimeoutError, BetterLockInternalError, BetterLockInvalidArgumentError, BetterLockJobAbortedError, BetterLockQueueOverflowError, BetterLockWaitTimeoutError } from './errors';
3
+ import { ILockJobOptions as BetterLockJobOptions, IOptions as BetterLockOptions } from './options';
4
+ import { IErrorName as BetterLockErrorName, IExecutor as BetterLockExecutor, ILockKey as BetterLockKey } from './types';
5
+ export { BetterLockOptions, BetterLockJobOptions, BetterLockExecutor, BetterLockKey, BetterLockErrorName, BetterLockError, BetterLockExecutionTimeoutError, BetterLockInternalError, BetterLockInvalidArgumentError, BetterLockJobAbortedError, BetterLockQueueOverflowError, BetterLockWaitTimeoutError, };
6
+ export declare const BetterLock: typeof BetterLockUnadorned & {
7
+ BetterLock: typeof BetterLockUnadorned;
8
+ Error: typeof BetterLockError;
9
+ InternalError: typeof BetterLockInternalError;
10
+ InvalidArgumentError: typeof BetterLockInvalidArgumentError;
11
+ WaitTimeoutError: typeof BetterLockWaitTimeoutError;
12
+ ExecutionTimeoutError: typeof BetterLockExecutionTimeoutError;
13
+ QueueOverflowError: typeof BetterLockQueueOverflowError;
14
+ JobAbortedError: typeof BetterLockJobAbortedError;
15
+ };
16
+ export default BetterLock;
package/dist/index.js ADDED
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BetterLock = exports.BetterLockWaitTimeoutError = exports.BetterLockQueueOverflowError = exports.BetterLockJobAbortedError = exports.BetterLockInvalidArgumentError = exports.BetterLockInternalError = exports.BetterLockExecutionTimeoutError = exports.BetterLockError = void 0;
4
+ var better_lock_1 = require("./better_lock");
5
+ var errors_1 = require("./errors");
6
+ Object.defineProperty(exports, "BetterLockError", { enumerable: true, get: function () { return errors_1.BetterLockError; } });
7
+ Object.defineProperty(exports, "BetterLockExecutionTimeoutError", { enumerable: true, get: function () { return errors_1.BetterLockExecutionTimeoutError; } });
8
+ Object.defineProperty(exports, "BetterLockInternalError", { enumerable: true, get: function () { return errors_1.BetterLockInternalError; } });
9
+ Object.defineProperty(exports, "BetterLockInvalidArgumentError", { enumerable: true, get: function () { return errors_1.BetterLockInvalidArgumentError; } });
10
+ Object.defineProperty(exports, "BetterLockJobAbortedError", { enumerable: true, get: function () { return errors_1.BetterLockJobAbortedError; } });
11
+ Object.defineProperty(exports, "BetterLockQueueOverflowError", { enumerable: true, get: function () { return errors_1.BetterLockQueueOverflowError; } });
12
+ Object.defineProperty(exports, "BetterLockWaitTimeoutError", { enumerable: true, get: function () { return errors_1.BetterLockWaitTimeoutError; } });
13
+ function attachExports(target, exports) {
14
+ Object.assign(target, exports);
15
+ return target;
16
+ }
17
+ exports.BetterLock = attachExports(better_lock_1.BetterLock, {
18
+ BetterLock: better_lock_1.BetterLock,
19
+ Error: errors_1.BetterLockError,
20
+ InternalError: errors_1.BetterLockInternalError,
21
+ InvalidArgumentError: errors_1.BetterLockInvalidArgumentError,
22
+ WaitTimeoutError: errors_1.BetterLockWaitTimeoutError,
23
+ ExecutionTimeoutError: errors_1.BetterLockExecutionTimeoutError,
24
+ QueueOverflowError: errors_1.BetterLockQueueOverflowError,
25
+ JobAbortedError: errors_1.BetterLockJobAbortedError,
26
+ });
27
+ exports.default = exports.BetterLock;
28
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,6CAAkE;AAClE,mCAQkB;AAehB,gGAtBA,wBAAe,OAsBA;AACf,gHAtBA,wCAA+B,OAsBA;AAC/B,wGAtBA,gCAAuB,OAsBA;AACvB,+GAtBA,uCAA8B,OAsBA;AAC9B,0GAtBA,kCAAyB,OAsBA;AACzB,6GAtBA,qCAA4B,OAsBA;AAC5B,2GAtBA,mCAA0B,OAsBA;AAG5B,SAAS,aAAa,CACpB,MAAe,EACf,OAAiB;IAEjB,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B,OAAO,MAAa,CAAC;AACvB,CAAC;AAEY,QAAA,UAAU,GAAG,aAAa,CAAC,wBAAmB,EAAE;IAC3D,UAAU,EAAE,wBAAmB;IAE/B,KAAK,EAAE,wBAAe;IACtB,aAAa,EAAE,gCAAuB;IACtC,oBAAoB,EAAE,uCAA8B;IACpD,gBAAgB,EAAE,mCAA0B;IAC5C,qBAAqB,EAAE,wCAA+B;IACtD,kBAAkB,EAAE,qCAA4B;IAChD,eAAe,EAAE,kCAAyB;CAC3C,CAAC,CAAC;AAEH,kBAAe,kBAAU,CAAC"}
@@ -0,0 +1,75 @@
1
+ import { ILockJobOptions } from './options';
2
+ import { ICallback, IExecutor } from './types';
3
+ /**
4
+ * Class that represents one scheduled job and its state. This is created every time user calls "acquire"
5
+ */
6
+ export declare class LockJob<TResult> {
7
+ static _lastId: number;
8
+ /** ID to uniquely identify this particular job */
9
+ id: any;
10
+ /**
11
+ * List of keys that will be locked. Always an array
12
+ */
13
+ keys: Array<string | null>;
14
+ /**
15
+ * Number of keys which this job is waiting on. Once this reaches 0, job will be executed
16
+ */
17
+ waiting_count: number;
18
+ /**
19
+ * Function that will be called inside the lock
20
+ */
21
+ executor: IExecutor<TResult>;
22
+ /**
23
+ * Function that will be called once job is done, whether it succeeds or times out.
24
+ * This is supplied by user in callback API, and generated internally otherwise.
25
+ */
26
+ callback: ICallback<TResult>;
27
+ /**
28
+ * Timestamp when job was created
29
+ */
30
+ enqueued_at: Date;
31
+ /**
32
+ * Timestamp when job was executed
33
+ */
34
+ executed_at: Date;
35
+ /**
36
+ * This is set when job ends, in case something holds a reference to it
37
+ */
38
+ ended_at: Date;
39
+ /**
40
+ * Options that apply to this particular job
41
+ */
42
+ options: ILockJobOptions;
43
+ /**
44
+ * Id of the wait timer
45
+ */
46
+ wait_timeout_id: any;
47
+ /**
48
+ * Id of the execution timer
49
+ */
50
+ execution_timeout_id: any;
51
+ /**
52
+ * Saved incoming stack, for the purpose of extending stack traces
53
+ */
54
+ incoming_stack: string;
55
+ constructor(keys: Array<string | null>, executor: IExecutor<TResult>, callback: ICallback<TResult>, options: ILockJobOptions);
56
+ toString(): string;
57
+ }
58
+ /**
59
+ * Class to hold pending, holding and executing jobs for one key
60
+ */
61
+ export declare class KeyQueue {
62
+ static readonly DEFAULT_QUEUE_KEY = "___DEFAULT_QUEUE_KEY___";
63
+ key: string;
64
+ /**
65
+ * Queue of jobs waiting to be executed.
66
+ * Jobs in this state are governed by the wait_timeout.
67
+ */
68
+ jobs: LockJob<any>[];
69
+ /**
70
+ * Active job that is holding this key. This job could be waiting on other keys or executing.
71
+ */
72
+ active: LockJob<any>;
73
+ constructor(key?: string);
74
+ toString(): string;
75
+ }
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KeyQueue = exports.LockJob = void 0;
4
+ /**
5
+ * Class that represents one scheduled job and its state. This is created every time user calls "acquire"
6
+ */
7
+ var LockJob = /** @class */ (function () {
8
+ function LockJob(keys, executor, callback, options) {
9
+ /** ID to uniquely identify this particular job */
10
+ this.id = undefined;
11
+ /**
12
+ * Timestamp when job was created
13
+ */
14
+ this.enqueued_at = new Date();
15
+ /**
16
+ * Timestamp when job was executed
17
+ */
18
+ this.executed_at = null;
19
+ /**
20
+ * This is set when job ends, in case something holds a reference to it
21
+ */
22
+ this.ended_at = null;
23
+ /**
24
+ * Id of the wait timer
25
+ */
26
+ this.wait_timeout_id = null;
27
+ /**
28
+ * Id of the execution timer
29
+ */
30
+ this.execution_timeout_id = null;
31
+ /**
32
+ * Saved incoming stack, for the purpose of extending stack traces
33
+ */
34
+ this.incoming_stack = null;
35
+ LockJob._lastId++;
36
+ this.id = LockJob._lastId;
37
+ this.keys = keys;
38
+ this.waiting_count = keys.length;
39
+ this.executor = executor;
40
+ this.callback = callback;
41
+ this.options = options;
42
+ }
43
+ LockJob.prototype.toString = function () {
44
+ return "Job #" + this.id + " [" + this.keys.join(', ') + "]";
45
+ };
46
+ LockJob._lastId = 0;
47
+ return LockJob;
48
+ }());
49
+ exports.LockJob = LockJob;
50
+ // *********************************************************************************************************************
51
+ /**
52
+ * Class to hold pending, holding and executing jobs for one key
53
+ */
54
+ var KeyQueue = /** @class */ (function () {
55
+ function KeyQueue(key) {
56
+ /**
57
+ * Queue of jobs waiting to be executed.
58
+ * Jobs in this state are governed by the wait_timeout.
59
+ */
60
+ this.jobs = [];
61
+ /**
62
+ * Active job that is holding this key. This job could be waiting on other keys or executing.
63
+ */
64
+ this.active = null;
65
+ this.key = key;
66
+ }
67
+ KeyQueue.prototype.toString = function () {
68
+ return this.key === KeyQueue.DEFAULT_QUEUE_KEY ? 'JobQueue' : "JobQueue<" + this.key + ">";
69
+ };
70
+ // We will use this key when user doesn't supply anything
71
+ KeyQueue.DEFAULT_QUEUE_KEY = '___DEFAULT_QUEUE_KEY___';
72
+ return KeyQueue;
73
+ }());
74
+ exports.KeyQueue = KeyQueue;
75
+ //# sourceMappingURL=internals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"internals.js","sourceRoot":"","sources":["../src/internals.ts"],"names":[],"mappings":";;;AAGA;;GAEG;AACH;IA8DE,iBACE,IAA0B,EAC1B,QAA4B,EAC5B,QAA4B,EAC5B,OAAwB;QA/D1B,kDAAkD;QAC3C,OAAE,GAAG,SAAS,CAAC;QAuBtB;;WAEG;QACI,gBAAW,GAAS,IAAI,IAAI,EAAE,CAAC;QAEtC;;WAEG;QACI,gBAAW,GAAS,IAAI,CAAC;QAEhC;;WAEG;QACI,aAAQ,GAAS,IAAI,CAAC;QAO7B;;WAEG;QACI,oBAAe,GAAG,IAAI,CAAC;QAE9B;;WAEG;QACI,yBAAoB,GAAG,IAAI,CAAC;QAEnC;;WAEG;QACI,mBAAc,GAAW,IAAI,CAAC;QAQnC,OAAO,CAAC,OAAO,EAAE,CAAC;QAClB,IAAI,CAAC,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,MAAM,CAAC;QACjC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,0BAAQ,GAAR;QACE,OAAO,UAAQ,IAAI,CAAC,EAAE,UAAK,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAG,CAAC;IACrD,CAAC;IA9EM,eAAO,GAAG,CAAC,CAAC;IA+ErB,cAAC;CAAA,AAhFD,IAgFC;AAhFY,0BAAO;AAkFpB,wHAAwH;AAExH;;GAEG;AACH;IAiBE,kBAAY,GAAY;QAXxB;;;WAGG;QACI,SAAI,GAAmB,EAAE,CAAC;QAEjC;;WAEG;QACI,WAAM,GAAiB,IAAI,CAAC;QAGjC,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACjB,CAAC;IAED,2BAAQ,GAAR;QACE,OAAO,IAAI,CAAC,GAAG,KAAK,QAAQ,CAAC,iBAAiB,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,cAAY,IAAI,CAAC,GAAG,MAAG,CAAC;IACxF,CAAC;IAtBD,yDAAyD;IACzC,0BAAiB,GAAG,yBAAyB,CAAC;IAsBhE,eAAC;CAAA,AAxBD,IAwBC;AAxBY,4BAAQ"}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Options that apply on LockJob
3
+ */
4
+ export interface ILockJobOptions {
5
+ /**
6
+ * How long can jobs wait in queue before timing out. Overrides BetterLockOptions value.
7
+ */
8
+ wait_timeout?: number | null;
9
+ /**
10
+ * How long can a job be executing before timing out. Null to disable timeout. Overrides BetterLockOptions value.
11
+ */
12
+ execution_timeout?: number | null;
13
+ /**
14
+ * In any error produced by BetterLock, extend the stack trace to include incoming trace. Overrides BetterLockOptions value.
15
+ */
16
+ extend_stack_traces?: boolean;
17
+ }
18
+ /**
19
+ * Options that apply on BetterLock instance
20
+ */
21
+ export interface IOptions extends ILockJobOptions {
22
+ /**
23
+ * How long can jobs wait in queue before timing out. Null to disable timeout.
24
+ */
25
+ wait_timeout?: number | null;
26
+ /**
27
+ * How long can a job be executing before timing out. Null to disable timeout.
28
+ * If you do that, though, and you have a swallowed callback, the lock can remain locked permanently.
29
+ */
30
+ execution_timeout?: number | null;
31
+ /**
32
+ * Max queue size for waiting jobs.
33
+ */
34
+ queue_size?: number | null;
35
+ /**
36
+ * Lock name. This will be written in all logs and error messages, to help you distinguish between different locks
37
+ */
38
+ name?: string;
39
+ /**
40
+ * Whether to log the internal actions. Set to true to use console.log. Alternatively, provide your own function
41
+ */
42
+ log?: boolean | ((msg: string) => void);
43
+ /**
44
+ * In any error produced by BetterLock, extend the stack trace to include incoming trace.
45
+ * Defaults to true.
46
+ */
47
+ extend_stack_traces?: boolean;
48
+ /**
49
+ * Function that detects whether value returned by executor is a promise.
50
+ * This will ducktype-sniff the returned value. Depending on your Promise library of choice,
51
+ * you might want to tighten or loosen this bit.
52
+ */
53
+ promise_tester?: (maybePromise: any) => boolean;
54
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"options.js","sourceRoot":"","sources":["../src/options.ts"],"names":[],"mappings":""}
@@ -0,0 +1,19 @@
1
+ import { ICallback } from './types';
2
+ export declare function isString(val: any): boolean;
3
+ export declare function isFunction(val: any): boolean;
4
+ export declare function isObject(val: any): boolean;
5
+ export declare function isNumber(val: any, includeInfinity?: boolean, includeNaN?: boolean): boolean;
6
+ export declare function noop(): void;
7
+ export declare function makeLog(name: any, doLog: any): (msg: string) => void;
8
+ /**
9
+ * Create a wrapped promise + callback construct
10
+ */
11
+ export declare function callbackWithPromise<TResult = any>(): Promise<TResult> & {
12
+ callback: ICallback<TResult>;
13
+ };
14
+ /**
15
+ * Assign properties from sources to target, skipping over undefined-s
16
+ * @param target Target object which will be mutated
17
+ * @param sources One or more source objects which will provide properties
18
+ */
19
+ export declare function assign<T>(target: T, sources: T[]): T;
package/dist/tools.js ADDED
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assign = exports.callbackWithPromise = exports.makeLog = exports.noop = exports.isNumber = exports.isObject = exports.isFunction = exports.isString = void 0;
4
+ function isString(val) {
5
+ return typeof val === 'string';
6
+ }
7
+ exports.isString = isString;
8
+ function isFunction(val) {
9
+ return typeof val === 'function';
10
+ }
11
+ exports.isFunction = isFunction;
12
+ function isObject(val) {
13
+ return typeof val === 'object' && val !== null && !Array.isArray(val);
14
+ }
15
+ exports.isObject = isObject;
16
+ function isNumber(val, includeInfinity, includeNaN) {
17
+ if (includeInfinity === void 0) { includeInfinity = false; }
18
+ if (includeNaN === void 0) { includeNaN = false; }
19
+ if (typeof val !== 'number') {
20
+ return false;
21
+ }
22
+ if (!includeInfinity && (val === Number.POSITIVE_INFINITY || val === Number.NEGATIVE_INFINITY)) {
23
+ return false;
24
+ }
25
+ if (!includeNaN && isNaN(val)) {
26
+ return false;
27
+ }
28
+ return true;
29
+ }
30
+ exports.isNumber = isNumber;
31
+ function noop() {
32
+ // Nothing
33
+ }
34
+ exports.noop = noop;
35
+ function makeLog(name, doLog) {
36
+ if (!doLog) {
37
+ return noop;
38
+ }
39
+ if (doLog === true) {
40
+ doLog = console.log.bind(console);
41
+ }
42
+ if (name) {
43
+ name = '[' + name + '] ';
44
+ }
45
+ return function log(msg) {
46
+ if (name) {
47
+ doLog(name + msg);
48
+ }
49
+ else {
50
+ doLog(msg);
51
+ }
52
+ };
53
+ }
54
+ exports.makeLog = makeLog;
55
+ /**
56
+ * Create a wrapped promise + callback construct
57
+ */
58
+ function callbackWithPromise() {
59
+ var callback;
60
+ var promise = new Promise(function (resolve, reject) {
61
+ callback = function (err, result) {
62
+ if (err) {
63
+ reject(err);
64
+ }
65
+ else {
66
+ resolve(result);
67
+ }
68
+ };
69
+ });
70
+ callback.promise = promise;
71
+ return callback;
72
+ }
73
+ exports.callbackWithPromise = callbackWithPromise;
74
+ /**
75
+ * Assign properties from sources to target, skipping over undefined-s
76
+ * @param target Target object which will be mutated
77
+ * @param sources One or more source objects which will provide properties
78
+ */
79
+ function assign(target, sources) {
80
+ for (var _i = 0, sources_1 = sources; _i < sources_1.length; _i++) {
81
+ var source = sources_1[_i];
82
+ if (!isObject(source)) {
83
+ // We must have an object to assign
84
+ continue;
85
+ }
86
+ for (var key in source) {
87
+ if (!source.hasOwnProperty(key)) {
88
+ continue;
89
+ }
90
+ var sourceValue = source[key];
91
+ if (sourceValue === undefined) {
92
+ // Do not overwrite undefineds
93
+ continue;
94
+ }
95
+ var targetValue = target[key];
96
+ if (isObject(sourceValue) && isObject(targetValue)) {
97
+ // Merge deep.
98
+ var cloneRoot = targetValue.constructor ? new targetValue.constructor() : {};
99
+ target[key] = assign(cloneRoot, [targetValue, sourceValue]);
100
+ continue;
101
+ }
102
+ // In all other cases, copy by reference
103
+ target[key] = sourceValue;
104
+ }
105
+ }
106
+ return target;
107
+ }
108
+ exports.assign = assign;
109
+ //# sourceMappingURL=tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.js","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":";;;AAEA,SAAgB,QAAQ,CAAC,GAAG;IAC1B,OAAO,OAAO,GAAG,KAAK,QAAQ,CAAC;AACjC,CAAC;AAFD,4BAEC;AAED,SAAgB,UAAU,CAAC,GAAG;IAC5B,OAAO,OAAO,GAAG,KAAK,UAAU,CAAC;AACnC,CAAC;AAFD,gC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5D,SAAS;aACV;YAED,wCAAwC;YACxC,MAAM,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC;SAC3B;KACF;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAhCD,wBAgCC"}
@@ -0,0 +1,23 @@
1
+ import * as errors from './errors';
2
+ declare type IErrorExports = typeof errors;
3
+ /**
4
+ * All error names that we can emit
5
+ */
6
+ export declare type IErrorName = keyof IErrorExports;
7
+ /**
8
+ * User-supplied callback. We support a "canonical" callback, with just error and result,
9
+ * but also old-school callbacks, with varargs return values.
10
+ */
11
+ export declare type ICallback<TResult> = TResult extends any[] ? (err?: Error, ...result: TResult) => void : (err?: Error, result?: TResult) => void;
12
+ /**
13
+ * Function that user will supply as the thing that will be running inside lock.
14
+ * It can either accept a done() function, or return a promise.
15
+ */
16
+ export declare type ICallbackExecutor<TResult> = (lockDone: ICallback<TResult>) => void;
17
+ export declare type IPromiseExecutor<TResult> = () => Promise<TResult>;
18
+ export declare type IExecutor<TResult> = ICallbackExecutor<TResult> | IPromiseExecutor<TResult>;
19
+ /**
20
+ * Key types that can be used for a lock.
21
+ */
22
+ export declare type ILockKey = string | number | null | undefined;
23
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/jest.config.js ADDED
@@ -0,0 +1,4 @@
1
+ module.exports = {
2
+ preset: 'ts-jest',
3
+ testEnvironment: 'node',
4
+ };
package/package.json CHANGED
@@ -1,10 +1,16 @@
1
1
  {
2
2
  "name": "better-lock",
3
- "version": "1.0.0",
3
+ "version": "2.0.1-beta",
4
4
  "description": "A (better) node.js lock library",
5
- "main": "index.js",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
6
7
  "scripts": {
7
- "test": "nyc mocha --recursive spec"
8
+ "prepublishOnly": "npm run build",
9
+ "build": "tsc",
10
+ "test": "jest",
11
+ "watch": "jest --watchAll",
12
+ "lint": "eslint ./src",
13
+ "coverage": "jest --coverage"
8
14
  },
9
15
  "repository": {
10
16
  "type": "git",
@@ -19,16 +25,32 @@
19
25
  "block",
20
26
  "sync"
21
27
  ],
28
+ "devDependencies": {
29
+ "@types/jest": "^26.0.23",
30
+ "@typescript-eslint/eslint-plugin": "^4.25.0",
31
+ "@typescript-eslint/parser": "^4.25.0",
32
+ "eslint": "^7.27.0",
33
+ "eslint-config-prettier": "^8.3.0",
34
+ "import-sort-style-module": "^6.0.0",
35
+ "jest": "^27.0.2",
36
+ "prettier": "latest",
37
+ "prettier-plugin-import-sort": "0.0.7",
38
+ "ts-jest": "^27.0.1",
39
+ "typescript": "^4.3.2"
40
+ },
22
41
  "author": "Ivan Pantic",
23
42
  "license": "MIT",
24
43
  "bugs": {
25
44
  "url": "https://github.com/panta82/better-lock/issues"
26
45
  },
27
46
  "homepage": "https://github.com/panta82/better-lock#readme",
28
- "devDependencies": {
29
- "chai": "^4.2.0",
30
- "mocha": "^5.2.0",
31
- "nyc": "^12.0.2",
32
- "prettier": "^1.16.1"
47
+ "importSort": {
48
+ ".ts, .tsx": {
49
+ "style": "module",
50
+ "parser": "typescript"
51
+ },
52
+ ".js, .jsx": {
53
+ "style": "module"
54
+ }
33
55
  }
34
56
  }