mongo-locks 3.0.2 → 3.1.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/README.md +5 -1
- package/dist/commonjs/package.json +3 -0
- package/dist/esm/index.js +113 -0
- package/dist/esm/package.json +3 -0
- package/package.json +28 -6
- package/index.ts +0 -125
- /package/dist/{index.js → commonjs/index.js} +0 -0
package/README.md
CHANGED
|
@@ -5,6 +5,10 @@ Simple and bountiful locks to avoid doing the same operation multiple times
|
|
|
5
5
|
The purpose of this package is simply to avoid doing the same thing twice at the same time
|
|
6
6
|
and make your system a bit more user-proof.
|
|
7
7
|
|
|
8
|
+
```bash
|
|
9
|
+
npm install mongo-locks
|
|
10
|
+
```
|
|
11
|
+
|
|
8
12
|
```ts
|
|
9
13
|
import { LockManager } from "mongo-locks";
|
|
10
14
|
import { MongoClient } from "mongodb";
|
|
@@ -13,7 +17,7 @@ const client = new MongoClient("mongodb://localhost:27017");
|
|
|
13
17
|
const lockManager = new LockManager(client.db().collection("mongo-locks"));
|
|
14
18
|
|
|
15
19
|
async function doStuff() {
|
|
16
|
-
await using lock = lockManager.lock("unique string key");
|
|
20
|
+
await using lock = await lockManager.lock("unique string key");
|
|
17
21
|
|
|
18
22
|
if (!lock) {
|
|
19
23
|
console.log("Lock already taken");
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { ObjectId } from "mongodb";
|
|
11
|
+
export class MongoLocksError extends Error {
|
|
12
|
+
constructor(message) {
|
|
13
|
+
super(message);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const makeKey = (key) => {
|
|
17
|
+
// Arrays mess up the unique MongoDB indexes
|
|
18
|
+
return Array.isArray(key) ? { _key_array: key } : key;
|
|
19
|
+
};
|
|
20
|
+
class Lock {
|
|
21
|
+
constructor(_id, action, collection) {
|
|
22
|
+
this._id = _id;
|
|
23
|
+
this.action = action;
|
|
24
|
+
this.collection = collection;
|
|
25
|
+
this.locked = true;
|
|
26
|
+
if (this.locked) {
|
|
27
|
+
(() => __awaiter(this, void 0, void 0, function* () {
|
|
28
|
+
while (this.locked) {
|
|
29
|
+
yield new Promise((resolve) => setTimeout(resolve, 10000));
|
|
30
|
+
yield this.refresh().catch(() => {
|
|
31
|
+
console.error("Failed to refresh lock", action);
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
}))();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Instead of calling `this.free` directly you can use the `using` syntax
|
|
39
|
+
*
|
|
40
|
+
* @returns true if the lock was successfully released. False if the lock was not found
|
|
41
|
+
*/
|
|
42
|
+
free() {
|
|
43
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
44
|
+
if (!this.locked) {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
this.locked = false;
|
|
48
|
+
const result = yield this.collection.deleteOne({ _id: this._id });
|
|
49
|
+
return result.deletedCount === 1;
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Refreshes the lock's TTL
|
|
54
|
+
*
|
|
55
|
+
* Automatically called every 10 seconds if the lock is still active, no
|
|
56
|
+
* need to call this manually
|
|
57
|
+
*
|
|
58
|
+
* @returns true if the lock was successfully refreshed. False if the lock was not found
|
|
59
|
+
*/
|
|
60
|
+
refresh() {
|
|
61
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
62
|
+
if (!this.locked) {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
const res = yield this.collection.updateOne({ _id: this._id }, { $set: { refreshedAt: new Date(), expiresAt: new Date(Date.now() + 60000) } });
|
|
66
|
+
this.locked = res.matchedCount === 1;
|
|
67
|
+
return this.locked;
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
[Symbol.dispose]() {
|
|
71
|
+
this.free();
|
|
72
|
+
}
|
|
73
|
+
[Symbol.asyncDispose]() {
|
|
74
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
75
|
+
return this.free();
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export class LockManager {
|
|
80
|
+
constructor(collection) {
|
|
81
|
+
this.MongoLocksError = MongoLocksError;
|
|
82
|
+
this.collection = collection;
|
|
83
|
+
collection.createIndex({ action: 1 }, { unique: true });
|
|
84
|
+
collection.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Creates a DB lock based on the key provided
|
|
88
|
+
*
|
|
89
|
+
* @returns a function that when called will release the lock
|
|
90
|
+
*/
|
|
91
|
+
lock(key) {
|
|
92
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
93
|
+
const lockId = makeKey(key);
|
|
94
|
+
const id = new ObjectId();
|
|
95
|
+
try {
|
|
96
|
+
yield this.collection.insertOne({
|
|
97
|
+
_id: id,
|
|
98
|
+
action: lockId,
|
|
99
|
+
createdAt: new Date(),
|
|
100
|
+
refreshedAt: new Date(),
|
|
101
|
+
expiresAt: new Date(Date.now() + 60000),
|
|
102
|
+
});
|
|
103
|
+
return new Lock(id, lockId, this.collection);
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
if (err instanceof Error && "code" in err && err.code === 11000) {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
throw err;
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mongo-locks",
|
|
3
|
-
"
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "3.1.0",
|
|
4
5
|
"description": "Simple and bountiful locks to avoid doing the same operation multiple times",
|
|
5
|
-
"main": "dist/index.js",
|
|
6
|
+
"main": "./dist/commonjs/index.js",
|
|
6
7
|
"scripts": {
|
|
7
8
|
"test": "echo \"Error: no test specified\" && exit 1",
|
|
8
|
-
"
|
|
9
|
-
"clean": "rm -Rf dist"
|
|
9
|
+
"prepare": "tshy"
|
|
10
10
|
},
|
|
11
11
|
"repository": {
|
|
12
12
|
"type": "git",
|
|
@@ -29,8 +29,9 @@
|
|
|
29
29
|
"mongodb": ">=4"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
|
-
"@types/node": "^
|
|
32
|
+
"@types/node": "^22.12.7",
|
|
33
33
|
"mongodb": "^6.5.0",
|
|
34
|
+
"tshy": "^3.1.0",
|
|
34
35
|
"typescript": "^5.4.5"
|
|
35
36
|
},
|
|
36
37
|
"files": [
|
|
@@ -38,5 +39,26 @@
|
|
|
38
39
|
"index.d.ts",
|
|
39
40
|
"index.ts",
|
|
40
41
|
"tsconfig.json"
|
|
41
|
-
]
|
|
42
|
+
],
|
|
43
|
+
"tshy": {
|
|
44
|
+
"exports": {
|
|
45
|
+
"./package.json": "./package.json",
|
|
46
|
+
".": "./src/index.ts"
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
"exports": {
|
|
50
|
+
"./package.json": "./package.json",
|
|
51
|
+
".": {
|
|
52
|
+
"import": {
|
|
53
|
+
"types": "./dist/esm/index.d.ts",
|
|
54
|
+
"default": "./dist/esm/index.js"
|
|
55
|
+
},
|
|
56
|
+
"require": {
|
|
57
|
+
"types": "./dist/commonjs/index.d.ts",
|
|
58
|
+
"default": "./dist/commonjs/index.js"
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
"types": "./dist/commonjs/index.d.ts",
|
|
63
|
+
"module": "./dist/esm/index.js"
|
|
42
64
|
}
|
package/index.ts
DELETED
|
@@ -1,125 +0,0 @@
|
|
|
1
|
-
import { Collection, ObjectId } from "mongodb";
|
|
2
|
-
|
|
3
|
-
export class MongoLocksError extends Error {
|
|
4
|
-
constructor(message?: string) {
|
|
5
|
-
super(message);
|
|
6
|
-
}
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
const makeKey = (key: unknown) => {
|
|
10
|
-
// Arrays mess up the unique MongoDB indexes
|
|
11
|
-
return Array.isArray(key) ? { _key_array: key } : key;
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
interface LockModel {
|
|
15
|
-
_id: ObjectId;
|
|
16
|
-
action: unknown;
|
|
17
|
-
createdAt: Date;
|
|
18
|
-
refreshedAt: Date;
|
|
19
|
-
expiresAt: Date;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
class Lock {
|
|
23
|
-
constructor(public _id: ObjectId, public action: unknown, public collection: Collection<LockModel>) {
|
|
24
|
-
if (this.locked) {
|
|
25
|
-
(async () => {
|
|
26
|
-
while (this.locked) {
|
|
27
|
-
await new Promise((resolve) => setTimeout(resolve, 10_000));
|
|
28
|
-
await this.refresh().catch(() => {
|
|
29
|
-
console.error("Failed to refresh lock", action);
|
|
30
|
-
});
|
|
31
|
-
}
|
|
32
|
-
})();
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
locked = true;
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Instead of calling `this.free` directly you can use the `using` syntax
|
|
40
|
-
*
|
|
41
|
-
* @returns true if the lock was successfully released. False if the lock was not found
|
|
42
|
-
*/
|
|
43
|
-
async free(): Promise<boolean> {
|
|
44
|
-
if (!this.locked) {
|
|
45
|
-
return false;
|
|
46
|
-
}
|
|
47
|
-
this.locked = false;
|
|
48
|
-
|
|
49
|
-
const result = await this.collection.deleteOne({ _id: this._id });
|
|
50
|
-
return result.deletedCount === 1;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* Refreshes the lock's TTL
|
|
55
|
-
*
|
|
56
|
-
* Automatically called every 10 seconds if the lock is still active, no
|
|
57
|
-
* need to call this manually
|
|
58
|
-
*
|
|
59
|
-
* @returns true if the lock was successfully refreshed. False if the lock was not found
|
|
60
|
-
*/
|
|
61
|
-
async refresh(): Promise<boolean> {
|
|
62
|
-
if (!this.locked) {
|
|
63
|
-
return false;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
const res = await this.collection.updateOne(
|
|
67
|
-
{ _id: this._id },
|
|
68
|
-
{ $set: { refreshedAt: new Date(), expiresAt: new Date(Date.now() + 60_000) } }
|
|
69
|
-
);
|
|
70
|
-
|
|
71
|
-
this.locked = res.matchedCount === 1;
|
|
72
|
-
|
|
73
|
-
return this.locked;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
[Symbol.dispose]() {
|
|
77
|
-
this.free();
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
async [Symbol.asyncDispose]() {
|
|
81
|
-
return this.free();
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export class LockManager {
|
|
86
|
-
collection: Collection<LockModel>;
|
|
87
|
-
MongoLocksError = MongoLocksError;
|
|
88
|
-
|
|
89
|
-
constructor(collection: Collection) {
|
|
90
|
-
this.collection = collection as unknown as Collection<LockModel>;
|
|
91
|
-
|
|
92
|
-
collection.createIndex({ action: 1 }, { unique: true });
|
|
93
|
-
collection.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* Creates a DB lock based on the key provided
|
|
98
|
-
*
|
|
99
|
-
* @returns a function that when called will release the lock
|
|
100
|
-
*/
|
|
101
|
-
async lock(key: unknown): Promise<Lock | null> {
|
|
102
|
-
const lockId = makeKey(key);
|
|
103
|
-
const id = new ObjectId();
|
|
104
|
-
|
|
105
|
-
try {
|
|
106
|
-
await this.collection.insertOne({
|
|
107
|
-
_id: id,
|
|
108
|
-
action: lockId,
|
|
109
|
-
createdAt: new Date(),
|
|
110
|
-
refreshedAt: new Date(),
|
|
111
|
-
expiresAt: new Date(Date.now() + 60_000),
|
|
112
|
-
});
|
|
113
|
-
|
|
114
|
-
return new Lock(id, lockId, this.collection);
|
|
115
|
-
} catch (err) {
|
|
116
|
-
if (err instanceof Error && "code" in err && err.code === 11000) {
|
|
117
|
-
return null;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
throw err;
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
export type { LockModel, Lock };
|
|
File without changes
|