@hazeljs/distributed-lock 0.4.0
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.
- package/LICENSE +192 -0
- package/README.md +184 -0
- package/dist/backends/index.d.ts +2 -0
- package/dist/backends/index.js +19 -0
- package/dist/backends/index.js.map +1 -0
- package/dist/backends/memory-backend.d.ts +17 -0
- package/dist/backends/memory-backend.js +89 -0
- package/dist/backends/memory-backend.js.map +1 -0
- package/dist/backends/redis-backend.d.ts +17 -0
- package/dist/backends/redis-backend.js +80 -0
- package/dist/backends/redis-backend.js.map +1 -0
- package/dist/backends/redis-backend.test.d.ts +1 -0
- package/dist/backends/redis-backend.test.js +41 -0
- package/dist/backends/redis-backend.test.js.map +1 -0
- package/dist/distributed-lock.decorator.d.ts +3 -0
- package/dist/distributed-lock.decorator.js +53 -0
- package/dist/distributed-lock.decorator.js.map +1 -0
- package/dist/distributed-lock.decorator.test.d.ts +1 -0
- package/dist/distributed-lock.decorator.test.js +114 -0
- package/dist/distributed-lock.decorator.test.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +21 -0
- package/dist/index.js.map +1 -0
- package/dist/interfaces.d.ts +20 -0
- package/dist/interfaces.js +3 -0
- package/dist/interfaces.js.map +1 -0
- package/dist/lock-manager.d.ts +13 -0
- package/dist/lock-manager.js +53 -0
- package/dist/lock-manager.js.map +1 -0
- package/dist/lock-manager.test.d.ts +1 -0
- package/dist/lock-manager.test.js +84 -0
- package/dist/lock-manager.test.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +50 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
Copyright 2024 HazelJS Team
|
|
6
|
+
|
|
7
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
8
|
+
you may not use this file except in compliance with the License.
|
|
9
|
+
You may obtain a copy of the License at
|
|
10
|
+
|
|
11
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
12
|
+
|
|
13
|
+
Unless required by applicable law or agreed to in writing, software
|
|
14
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
15
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
16
|
+
See the License for the specific language governing permissions and
|
|
17
|
+
limitations under the License.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
22
|
+
|
|
23
|
+
1. Definitions.
|
|
24
|
+
|
|
25
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
26
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
27
|
+
|
|
28
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
29
|
+
the copyright owner that is granting the License.
|
|
30
|
+
|
|
31
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
32
|
+
other entities that control, are controlled by, or are under common
|
|
33
|
+
control with that entity. For the purposes of this definition,
|
|
34
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
35
|
+
direction or management of such entity, whether by contract or
|
|
36
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
37
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
38
|
+
|
|
39
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
40
|
+
exercising permissions granted by this License.
|
|
41
|
+
|
|
42
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
43
|
+
including but not limited to software source code, documentation
|
|
44
|
+
source, and configuration files.
|
|
45
|
+
|
|
46
|
+
"Object" form shall mean any form resulting from mechanical
|
|
47
|
+
transformation or translation of a Source form, including but
|
|
48
|
+
not limited to compiled object code, generated documentation,
|
|
49
|
+
and conversions to other media types.
|
|
50
|
+
|
|
51
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
52
|
+
Object form, made available under the License, as indicated by a
|
|
53
|
+
copyright notice that is included in or attached to the work
|
|
54
|
+
(an example is provided in the Appendix below).
|
|
55
|
+
|
|
56
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
57
|
+
form, that is based on (or derived from) the Work and for which the
|
|
58
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
59
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
60
|
+
of this License, Derivative Works shall not include works that remain
|
|
61
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
62
|
+
the Work and Derivative Works thereof.
|
|
63
|
+
|
|
64
|
+
"Contribution" shall mean any work of authorship, including
|
|
65
|
+
the original version of the Work and any modifications or additions
|
|
66
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
67
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
68
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
69
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
70
|
+
means any form of electronic, verbal, or written communication sent
|
|
71
|
+
to the Licensor or its representatives, including but not limited to
|
|
72
|
+
communication on electronic mailing lists, source code control systems,
|
|
73
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
74
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
75
|
+
excluding communication that is conspicuously marked or otherwise
|
|
76
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
77
|
+
|
|
78
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
79
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
80
|
+
subsequently incorporated within the Work.
|
|
81
|
+
|
|
82
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
83
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
84
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
85
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
86
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
87
|
+
Work and such Derivative Works in Source or Object form.
|
|
88
|
+
|
|
89
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
90
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
91
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
92
|
+
(except as stated in this section) patent license to make, have made,
|
|
93
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
94
|
+
where such license applies only to those patent claims licensable
|
|
95
|
+
by such Contributor that are necessarily infringed by their
|
|
96
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
97
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
98
|
+
institute patent litigation against any entity (including a
|
|
99
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
100
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
101
|
+
or contributory patent infringement, then any patent licenses
|
|
102
|
+
granted to You under this License for that Work shall terminate
|
|
103
|
+
as of the date such litigation is filed.
|
|
104
|
+
|
|
105
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
106
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
107
|
+
modifications, and in Source or Object form, provided that You
|
|
108
|
+
meet the following conditions:
|
|
109
|
+
|
|
110
|
+
(a) You must give any other recipients of the Work or
|
|
111
|
+
Derivative Works a copy of this License; and
|
|
112
|
+
|
|
113
|
+
(b) You must cause any modified files to carry prominent notices
|
|
114
|
+
stating that You changed the files; and
|
|
115
|
+
|
|
116
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
117
|
+
that You distribute, all copyright, patent, trademark, and
|
|
118
|
+
attribution notices from the Source form of the Work,
|
|
119
|
+
excluding those notices that do not pertain to any part of
|
|
120
|
+
the Derivative Works; and
|
|
121
|
+
|
|
122
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
123
|
+
distribution, then any Derivative Works that You distribute must
|
|
124
|
+
include a readable copy of the attribution notices contained
|
|
125
|
+
within such NOTICE file, excluding those notices that do not
|
|
126
|
+
pertain to any part of the Derivative Works, in at least one
|
|
127
|
+
of the following places: within a NOTICE text file distributed
|
|
128
|
+
as part of the Derivative Works; within the Source form or
|
|
129
|
+
documentation, if provided along with the Derivative Works; or,
|
|
130
|
+
within a display generated by the Derivative Works, if and
|
|
131
|
+
wherever such third-party notices normally appear. The contents
|
|
132
|
+
of the NOTICE file are for informational purposes only and
|
|
133
|
+
do not modify the License. You may add Your own attribution
|
|
134
|
+
notices within Derivative Works that You distribute, alongside
|
|
135
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
136
|
+
that such additional attribution notices cannot be construed
|
|
137
|
+
as modifying the License.
|
|
138
|
+
|
|
139
|
+
You may add Your own copyright statement to Your modifications and
|
|
140
|
+
may provide additional or different license terms and conditions
|
|
141
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
142
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
143
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
144
|
+
the conditions stated in this License.
|
|
145
|
+
|
|
146
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
147
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
148
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
149
|
+
this License, without any additional terms or conditions.
|
|
150
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
151
|
+
the terms of any separate license agreement you may have executed
|
|
152
|
+
with Licensor regarding such Contributions.
|
|
153
|
+
|
|
154
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
155
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
156
|
+
except as required for reasonable and customary use in describing the
|
|
157
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
158
|
+
|
|
159
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
160
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
161
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
162
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
163
|
+
implied, including, without limitation, any warranties or conditions
|
|
164
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
165
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
166
|
+
appropriateness of using or redistributing the Work and assume any
|
|
167
|
+
risks associated with Your exercise of permissions under this License.
|
|
168
|
+
|
|
169
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
170
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
171
|
+
unless required by applicable law (such as deliberate and grossly
|
|
172
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
173
|
+
liable to You for damages, including any direct, indirect, special,
|
|
174
|
+
incidental, or consequential damages of any character arising as a
|
|
175
|
+
result of this License or out of the use or inability to use the
|
|
176
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
177
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
178
|
+
other commercial damages or losses), even if such Contributor
|
|
179
|
+
has been advised of the possibility of such damages.
|
|
180
|
+
|
|
181
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
182
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
183
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
184
|
+
or other liability obligations and/or rights consistent with this
|
|
185
|
+
License. However, in accepting such obligations, You may act only
|
|
186
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
187
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
188
|
+
defend, and hold each Contributor harmless for any liability
|
|
189
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
190
|
+
of your accepting any such warranty or additional liability.
|
|
191
|
+
|
|
192
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# @hazeljs/distributed-lock
|
|
2
|
+
|
|
3
|
+
**Distributed Locking for HazelJS. Mutual exclusion across all your nodes, simplified.**
|
|
4
|
+
|
|
5
|
+
Ensure that your critical code paths are only executed by one instance at a time. HazelJS Distributed Lock provides a unified interface for multiple backends (Redis, In-Memory) and a powerful decorator-based API with dynamic key resolution.
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/@hazeljs/distributed-lock)
|
|
8
|
+
[](https://www.npmjs.com/package/@hazeljs/distributed-lock)
|
|
9
|
+
[](https://www.apache.org/licenses/LICENSE-2.0)
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- 🔒 **Decorator-Based API** — Use `@DistributedLock()` for declarative, method-level locking across your distributed system.
|
|
14
|
+
- 📂 **Multiple Backends** — First-class support for **Redis** (production) and **Memory** (local development/testing).
|
|
15
|
+
- 🔢 **Dynamic Key Resolution** — Support for template placeholders (e.g., `{id}`, `{user.token}`) that automatically resolve from method arguments.
|
|
16
|
+
- ⚖️ **Atomic Mutual Exclusion** — Guarantees that exactly one process executes a given snippet at any moment across all nodes.
|
|
17
|
+
- 🔄 **Wait & Retry Strategies** — Highly configurable lock acquisition logic, including retry counts, delays, and TTLs.
|
|
18
|
+
- 🧹 **Automatic Cleanup** — Locks are automatically released upon method completion, regardless of success or failure.
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npm install @hazeljs/distributed-lock
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
### Optional Peer Dependencies
|
|
29
|
+
|
|
30
|
+
For production environments using Redis, you'll need the following:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
npm install redis
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## Quick Start (Decorator)
|
|
39
|
+
|
|
40
|
+
The easiest way to use distributed locking is through the `@DistributedLock` decorator.
|
|
41
|
+
|
|
42
|
+
### 1. Simple Locking
|
|
43
|
+
|
|
44
|
+
Lock a method for a specific user based on an argument.
|
|
45
|
+
|
|
46
|
+
```typescript
|
|
47
|
+
import { DistributedLock } from '@hazeljs/distributed-lock';
|
|
48
|
+
|
|
49
|
+
class UserProfileService {
|
|
50
|
+
@DistributedLock({
|
|
51
|
+
key: 'update-profile-{userId}',
|
|
52
|
+
ttl: 10000,
|
|
53
|
+
wait: true
|
|
54
|
+
})
|
|
55
|
+
async updateProfile(userId: string, data: any) {
|
|
56
|
+
// This code is now thread-safe across all distributed nodes
|
|
57
|
+
// for this specific userId.
|
|
58
|
+
return await this.saveProfile(userId, data);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### 2. Manual Programmatic API
|
|
64
|
+
|
|
65
|
+
You can also acquire and release locks manually using the `LockManager`.
|
|
66
|
+
|
|
67
|
+
```typescript
|
|
68
|
+
import { LockManager } from '@hazeljs/distributed-lock';
|
|
69
|
+
|
|
70
|
+
const lockManager = LockManager.getInstance();
|
|
71
|
+
|
|
72
|
+
async function myTask() {
|
|
73
|
+
const lock = await lockManager.acquire({
|
|
74
|
+
key: 'manual-task-lock',
|
|
75
|
+
ttl: 5000,
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
if (!lock) return; // Could not acquire lock
|
|
79
|
+
|
|
80
|
+
try {
|
|
81
|
+
// Perform critical task...
|
|
82
|
+
} finally {
|
|
83
|
+
// Always release in finally block
|
|
84
|
+
await lock.release();
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## Lock Backends
|
|
92
|
+
|
|
93
|
+
Choose the backend that fits your deployment strategy.
|
|
94
|
+
|
|
95
|
+
### In-Memory (Default)
|
|
96
|
+
|
|
97
|
+
Great for development or single-node deployments.
|
|
98
|
+
|
|
99
|
+
```typescript
|
|
100
|
+
import { LockManager } from '@hazeljs/distributed-lock';
|
|
101
|
+
|
|
102
|
+
const lockManager = LockManager.getInstance();
|
|
103
|
+
lockManager.setDefaultBackend('memory');
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### Redis (Production)
|
|
107
|
+
|
|
108
|
+
Recommended for multi-node production systems.
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
import { LockManager } from '@hazeljs/distributed-lock';
|
|
112
|
+
|
|
113
|
+
const lockManager = LockManager.getInstance();
|
|
114
|
+
|
|
115
|
+
lockManager.setupRedis({
|
|
116
|
+
url: 'redis://localhost:6379',
|
|
117
|
+
}, 'redis-prod');
|
|
118
|
+
|
|
119
|
+
lockManager.setDefaultBackend('redis-prod');
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## Backend Comparison
|
|
125
|
+
|
|
126
|
+
| | In-Memory | Redis | Custom |
|
|
127
|
+
|---|:---:|:---:|:---:|
|
|
128
|
+
| **Distributed** | ❌ (Single node) | ✅ (All nodes) | ✅ (Interface-based) |
|
|
129
|
+
| **Setup** | None | Required | Custom impl |
|
|
130
|
+
| **Best For** | Development / Testing | Production / High Load | Specialized systems |
|
|
131
|
+
| **Performance** | Nano-seconds | Milli-seconds | Backend-dependent |
|
|
132
|
+
|
|
133
|
+
---
|
|
134
|
+
|
|
135
|
+
## Configuration Options
|
|
136
|
+
|
|
137
|
+
| Option | Type | Description |
|
|
138
|
+
| --- | --- | --- |
|
|
139
|
+
| `key` | `string` | The unique lock identifier. Supports `{param}` placeholders from method args. |
|
|
140
|
+
| `ttl` | `number` | Time-To-Live in milliseconds. Default: `5000`. |
|
|
141
|
+
| `wait` | `boolean` | If true, will wait for the lock if held. Default: `false`. |
|
|
142
|
+
| `retryCount`| `number` | Number of retries if `wait` is true. Default: `3`. |
|
|
143
|
+
| `retryDelay`| `number` | Time between retries in milliseconds. Default: `100`. |
|
|
144
|
+
| `backend` | `string` | Override the default backend (e.g., `'memory'`, `'redis'`). |
|
|
145
|
+
|
|
146
|
+
---
|
|
147
|
+
|
|
148
|
+
## API Reference
|
|
149
|
+
|
|
150
|
+
### `LockManager` (Singleton)
|
|
151
|
+
|
|
152
|
+
```typescript
|
|
153
|
+
class LockManager {
|
|
154
|
+
static getInstance(): LockManager;
|
|
155
|
+
registerBackend(name: string, backend: ILockBackend): void;
|
|
156
|
+
setDefaultBackend(name: string): void;
|
|
157
|
+
acquire(options: LockOptions): Promise<ILock | null>;
|
|
158
|
+
setupRedis(redisOptions: any, name?: string): void;
|
|
159
|
+
}
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### `Interfaces`
|
|
163
|
+
|
|
164
|
+
- **`ILock`** — An acquired lock. Contains `release(): Promise<void>`.
|
|
165
|
+
- **`ILockBackend`** — The interface for implementing custom lock providers.
|
|
166
|
+
|
|
167
|
+
---
|
|
168
|
+
|
|
169
|
+
## Use Cases
|
|
170
|
+
|
|
171
|
+
- 💰 **Payment Processing** — Preventing double-charging on concurrent requests.
|
|
172
|
+
- 📦 **Inventory Management** — Ensuring stock counts remain accurate across multiple instances.
|
|
173
|
+
- 👤 **Global Singletons** — Guaranteeing that only one cron job or worker runs a task globally.
|
|
174
|
+
- 🏗️ **Resource Provisioning** — Atomically creating cloud resources like databases or VMs.
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
## License
|
|
179
|
+
|
|
180
|
+
Apache-2.0
|
|
181
|
+
|
|
182
|
+
## Contributing
|
|
183
|
+
|
|
184
|
+
Contributions are welcome! See [CONTRIBUTING.md](../../CONTRIBUTING.md) for details.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./memory-backend"), exports);
|
|
18
|
+
__exportStar(require("./redis-backend"), exports);
|
|
19
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/backends/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,mDAAiC;AACjC,kDAAgC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { ILock, ILockBackend, LockOptions } from '../interfaces';
|
|
2
|
+
export declare class MemoryLock implements ILock {
|
|
3
|
+
private readonly backend;
|
|
4
|
+
private readonly key;
|
|
5
|
+
private readonly identifier;
|
|
6
|
+
private expiration;
|
|
7
|
+
constructor(backend: MemoryLockBackend, key: string, identifier: string, expiration: number);
|
|
8
|
+
release(): Promise<void>;
|
|
9
|
+
extend(ttl: number): Promise<boolean>;
|
|
10
|
+
}
|
|
11
|
+
export declare class MemoryLockBackend implements ILockBackend {
|
|
12
|
+
private readonly locks;
|
|
13
|
+
acquire(options: LockOptions): Promise<ILock | null>;
|
|
14
|
+
release(key: string, identifier: string): Promise<void>;
|
|
15
|
+
extend(key: string, identifier: string, ttl: number): Promise<boolean>;
|
|
16
|
+
close(): Promise<void>;
|
|
17
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MemoryLockBackend = exports.MemoryLock = void 0;
|
|
4
|
+
class MemoryLock {
|
|
5
|
+
constructor(backend, key, identifier, expiration) {
|
|
6
|
+
this.backend = backend;
|
|
7
|
+
this.key = key;
|
|
8
|
+
this.identifier = identifier;
|
|
9
|
+
this.expiration = expiration;
|
|
10
|
+
}
|
|
11
|
+
async release() {
|
|
12
|
+
return this.backend.release(this.key, this.identifier);
|
|
13
|
+
}
|
|
14
|
+
async extend(ttl) {
|
|
15
|
+
return this.backend.extend(this.key, this.identifier, ttl);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
exports.MemoryLock = MemoryLock;
|
|
19
|
+
class MemoryLockBackend {
|
|
20
|
+
constructor() {
|
|
21
|
+
this.locks = new Map();
|
|
22
|
+
}
|
|
23
|
+
async acquire(options) {
|
|
24
|
+
const { key, ttl = 30000, retry } = options;
|
|
25
|
+
const identifier = Math.random().toString(36).substring(2);
|
|
26
|
+
const attempt = async () => {
|
|
27
|
+
const current = this.locks.get(key);
|
|
28
|
+
const now = Date.now();
|
|
29
|
+
if (!current || current.expiration < now) {
|
|
30
|
+
if (current?.timer) {
|
|
31
|
+
clearTimeout(current.timer);
|
|
32
|
+
}
|
|
33
|
+
const expiration = now + ttl;
|
|
34
|
+
const timer = setTimeout(() => {
|
|
35
|
+
this.release(key, identifier);
|
|
36
|
+
}, ttl);
|
|
37
|
+
this.locks.set(key, { identifier, expiration, timer });
|
|
38
|
+
return new MemoryLock(this, key, identifier, expiration);
|
|
39
|
+
}
|
|
40
|
+
return null;
|
|
41
|
+
};
|
|
42
|
+
let lock = await attempt();
|
|
43
|
+
if (lock)
|
|
44
|
+
return lock;
|
|
45
|
+
if (retry) {
|
|
46
|
+
for (let i = 0; i < retry.attempts; i++) {
|
|
47
|
+
await new Promise((resolve) => setTimeout(resolve, retry.delay));
|
|
48
|
+
lock = await attempt();
|
|
49
|
+
if (lock)
|
|
50
|
+
return lock;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
async release(key, identifier) {
|
|
56
|
+
const current = this.locks.get(key);
|
|
57
|
+
if (current && current.identifier === identifier) {
|
|
58
|
+
if (current.timer) {
|
|
59
|
+
clearTimeout(current.timer);
|
|
60
|
+
}
|
|
61
|
+
this.locks.delete(key);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
async extend(key, identifier, ttl) {
|
|
65
|
+
const current = this.locks.get(key);
|
|
66
|
+
if (current && current.identifier === identifier) {
|
|
67
|
+
if (current.timer) {
|
|
68
|
+
clearTimeout(current.timer);
|
|
69
|
+
}
|
|
70
|
+
const expiration = Date.now() + ttl;
|
|
71
|
+
const timer = setTimeout(() => {
|
|
72
|
+
this.release(key, identifier);
|
|
73
|
+
}, ttl);
|
|
74
|
+
this.locks.set(key, { identifier, expiration, timer });
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
async close() {
|
|
80
|
+
for (const lock of this.locks.values()) {
|
|
81
|
+
if (lock.timer) {
|
|
82
|
+
clearTimeout(lock.timer);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
this.locks.clear();
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
exports.MemoryLockBackend = MemoryLockBackend;
|
|
89
|
+
//# sourceMappingURL=memory-backend.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memory-backend.js","sourceRoot":"","sources":["../../src/backends/memory-backend.ts"],"names":[],"mappings":";;;AAEA,MAAa,UAAU;IACrB,YACmB,OAA0B,EAC1B,GAAW,EACX,UAAkB,EAC3B,UAAkB;QAHT,YAAO,GAAP,OAAO,CAAmB;QAC1B,QAAG,GAAH,GAAG,CAAQ;QACX,eAAU,GAAV,UAAU,CAAQ;QAC3B,eAAU,GAAV,UAAU,CAAQ;IACzB,CAAC;IAEJ,KAAK,CAAC,OAAO;QACX,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IACzD,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,GAAW;QACtB,OAAO,IAAI,CAAC,O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G,EAAE,GAAG,GAAG,CAAC;YACpC,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;gBAC5B,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;YAChC,CAAC,EAAE,GAAG,CAAC,CAAC;YAER,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,UAAU,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC,CAAC;YACvD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,KAAK,CAAC,KAAK;QACT,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC;YACvC,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;gBACf,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAC3B,CAAC;QACH,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;CACF;AAhFD,8CAgFC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { ILock, ILockBackend, LockOptions } from '../interfaces';
|
|
2
|
+
export declare class RedisLock implements ILock {
|
|
3
|
+
private readonly backend;
|
|
4
|
+
private readonly key;
|
|
5
|
+
private readonly identifier;
|
|
6
|
+
constructor(backend: RedisLockBackend, key: string, identifier: string);
|
|
7
|
+
release(): Promise<void>;
|
|
8
|
+
extend(ttl: number): Promise<boolean>;
|
|
9
|
+
}
|
|
10
|
+
export declare class RedisLockBackend implements ILockBackend {
|
|
11
|
+
private readonly redis;
|
|
12
|
+
constructor(redisOptions: unknown);
|
|
13
|
+
acquire(options: LockOptions): Promise<ILock | null>;
|
|
14
|
+
release(key: string, identifier: string): Promise<void>;
|
|
15
|
+
extend(key: string, identifier: string, ttl: number): Promise<boolean>;
|
|
16
|
+
close(): Promise<void>;
|
|
17
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.RedisLockBackend = exports.RedisLock = void 0;
|
|
7
|
+
const ioredis_1 = __importDefault(require("ioredis"));
|
|
8
|
+
class RedisLock {
|
|
9
|
+
constructor(backend, key, identifier) {
|
|
10
|
+
this.backend = backend;
|
|
11
|
+
this.key = key;
|
|
12
|
+
this.identifier = identifier;
|
|
13
|
+
}
|
|
14
|
+
async release() {
|
|
15
|
+
return this.backend.release(this.key, this.identifier);
|
|
16
|
+
}
|
|
17
|
+
async extend(ttl) {
|
|
18
|
+
return this.backend.extend(this.key, this.identifier, ttl);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
exports.RedisLock = RedisLock;
|
|
22
|
+
class RedisLockBackend {
|
|
23
|
+
constructor(redisOptions) {
|
|
24
|
+
if (redisOptions && typeof redisOptions.set === 'function') {
|
|
25
|
+
this.redis = redisOptions;
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
this.redis = new ioredis_1.default(redisOptions);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
async acquire(options) {
|
|
32
|
+
const { key, ttl = 30000, retry } = options;
|
|
33
|
+
const identifier = Math.random().toString(36).substring(2);
|
|
34
|
+
const attempt = async () => {
|
|
35
|
+
const result = await this.redis.set(key, identifier, 'PX', ttl, 'NX');
|
|
36
|
+
if (result === 'OK') {
|
|
37
|
+
return new RedisLock(this, key, identifier);
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
};
|
|
41
|
+
let lock = await attempt();
|
|
42
|
+
if (lock)
|
|
43
|
+
return lock;
|
|
44
|
+
if (retry) {
|
|
45
|
+
for (let i = 0; i < retry.attempts; i++) {
|
|
46
|
+
await new Promise((resolve) => setTimeout(resolve, retry.delay));
|
|
47
|
+
lock = await attempt();
|
|
48
|
+
if (lock)
|
|
49
|
+
return lock;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
async release(key, identifier) {
|
|
55
|
+
const script = `
|
|
56
|
+
if redis.call("get", KEYS[1]) == ARGV[1] then
|
|
57
|
+
return redis.call("del", KEYS[1])
|
|
58
|
+
else
|
|
59
|
+
return 0
|
|
60
|
+
end
|
|
61
|
+
`;
|
|
62
|
+
await this.redis.eval(script, 1, key, identifier);
|
|
63
|
+
}
|
|
64
|
+
async extend(key, identifier, ttl) {
|
|
65
|
+
const script = `
|
|
66
|
+
if redis.call("get", KEYS[1]) == ARGV[1] then
|
|
67
|
+
return redis.call("pexpire", KEYS[1], ARGV[2])
|
|
68
|
+
else
|
|
69
|
+
return 0
|
|
70
|
+
end
|
|
71
|
+
`;
|
|
72
|
+
const result = await this.redis.eval(script, 1, key, identifier, ttl);
|
|
73
|
+
return result === 1;
|
|
74
|
+
}
|
|
75
|
+
async close() {
|
|
76
|
+
await this.redis.quit();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
exports.RedisLockBackend = RedisLockBackend;
|
|
80
|
+
//# sourceMappingURL=redis-backend.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redis-backend.js","sourceRoot":"","sources":["../../src/backends/redis-backend.ts"],"names":[],"mappings":";;;;;;AAAA,sDAA4B;AAG5B,MAAa,SAAS;IACpB,YACmB,OAAyB,EACzB,GAAW,EACX,UAAkB;QAFlB,YAAO,GAAP,OAAO,CAAkB;QACzB,QAAG,GAAH,GAAG,CAAQ;QACX,eAAU,GAAV,UAAU,CAAQ;IAClC,CAAC;IAEJ,KAAK,CAAC,OAAO;QACX,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IACzD,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,GAAW;QACtB,OA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M,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;gBACjE,IAAI,GAAG,MAAM,OAAO,EAAE,CAAC;gBACvB,IAAI,IAAI;oBAAE,OAAO,IAAI,CAAC;YACxB,CAAC;QACH,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,GAAW,EAAE,UAAkB;QAE3C,MAAM,MAAM,GAAG;;;;;;KAMd,CAAC;QACF,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,GAAG,EAAE,UAAU,CAAC,CAAC;IACpD,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,GAAW,EAAE,UAAkB,EAAE,GAAW;QACvD,MAAM,MAAM,GAAG;;;;;;KAMd,CAAC;QACF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QACtE,OAAO,MAAM,KAAK,CAAC,CAAC;IACtB,CAAC;IAED,KAAK,CAAC,KAAK;QACT,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;IAC1B,CAAC;CACF;AAlED,4CAkEC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const redis_backend_1 = require("./redis-backend");
|
|
4
|
+
describe('RedisLockBackend', () => {
|
|
5
|
+
let backend;
|
|
6
|
+
let redis;
|
|
7
|
+
beforeEach(() => {
|
|
8
|
+
redis = {
|
|
9
|
+
set: jest.fn(),
|
|
10
|
+
eval: jest.fn(),
|
|
11
|
+
quit: jest.fn().mockResolvedValue('OK'),
|
|
12
|
+
};
|
|
13
|
+
backend = new redis_backend_1.RedisLockBackend(redis);
|
|
14
|
+
});
|
|
15
|
+
it('should acquire a lock', async () => {
|
|
16
|
+
redis.set.mockResolvedValue('OK');
|
|
17
|
+
const lock = await backend.acquire({ key: 'test-lock', ttl: 1000 });
|
|
18
|
+
expect(lock).not.toBeNull();
|
|
19
|
+
expect(redis.set).toHaveBeenCalledWith('test-lock', expect.any(String), 'PX', 1000, 'NX');
|
|
20
|
+
});
|
|
21
|
+
it('should return null if lock acquisition fails', async () => {
|
|
22
|
+
redis.set.mockResolvedValue(null);
|
|
23
|
+
const lock = await backend.acquire({ key: 'test-lock', ttl: 1000 });
|
|
24
|
+
expect(lock).toBeNull();
|
|
25
|
+
});
|
|
26
|
+
it('should release a lock using eval', async () => {
|
|
27
|
+
redis.set.mockResolvedValue('OK');
|
|
28
|
+
const lock = await backend.acquire({ key: 'test-lock', ttl: 1000 });
|
|
29
|
+
await lock?.release();
|
|
30
|
+
expect(redis.eval).toHaveBeenCalled();
|
|
31
|
+
});
|
|
32
|
+
it('should extend a lock using eval', async () => {
|
|
33
|
+
redis.set.mockResolvedValue('OK');
|
|
34
|
+
const lock = await backend.acquire({ key: 'test-lock', ttl: 1000 });
|
|
35
|
+
redis.eval.mockResolvedValue(1);
|
|
36
|
+
const extended = await lock?.extend(2000);
|
|
37
|
+
expect(extended).toBe(true);
|
|
38
|
+
expect(redis.eval).toHaveBeenCalled();
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
//# sourceMappingURL=redis-backend.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redis-backend.test.js","sourceRoot":"","sources":["../../src/backends/redis-backend.test.ts"],"names":[],"mappings":";;AAAA,mDAAmD;AAEnD,QAAQ,CAAC,kBAAkB,EAAE,GAAG,EAAE;IAChC,IAAI,OAAyB,CAAC;IAC9B,IAAI,KAAU,CAAC;IAEf,UAAU,CAAC,GAAG,EAAE;QACd,KAAK,GAAG;YACN,GAAG,EA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