-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathMongoLockManager.ts
123 lines (107 loc) · 2.57 KB
/
MongoLockManager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import * as framework from '@powersync/lib-services-framework';
import * as bson from 'bson';
import * as mongo from 'mongodb';
/**
* Lock Document Schema
*/
export type Lock = {
name: string;
active_lock?: {
lock_id: bson.ObjectId;
ts: Date;
};
};
export type Collection = mongo.Collection<Lock>;
export type MongoLockManagerParams = framework.locks.LockManagerParams & {
collection: Collection;
};
const DEFAULT_LOCK_TIMEOUT = 60 * 1000; // 1 minute
export class MongoLockManager extends framework.locks.AbstractLockManager {
collection: Collection;
constructor(params: MongoLockManagerParams) {
super(params);
this.collection = params.collection;
}
protected async acquireHandle(options?: framework.LockAcquireOptions): Promise<framework.LockHandle | null> {
const lock_id = await this.getHandle();
if (!lock_id) {
return null;
}
return {
refresh: () => this.refreshHandle(lock_id),
release: () => this.releaseHandle(lock_id)
};
}
protected async refreshHandle(lock_id: bson.ObjectId) {
const res = await this.collection.updateOne(
{
'active_lock.lock_id': lock_id
},
{
$set: {
'active_lock.ts': new Date()
}
}
);
if (res.modifiedCount === 0) {
throw new Error('Lock not found, could not refresh');
}
}
protected async getHandle() {
const now = new Date();
const lock_timeout = this.params.timeout ?? DEFAULT_LOCK_TIMEOUT;
const lock_id = new bson.ObjectId();
const { name } = this.params;
await this.collection.updateOne(
{
name
},
{
$setOnInsert: {
name
}
},
{
upsert: true
}
);
const expired_ts = now.getTime() - lock_timeout;
const res = await this.collection.updateOne(
{
$and: [
{ name: name },
{
$or: [{ active_lock: { $exists: false } }, { 'active_lock.ts': { $lte: new Date(expired_ts) } }]
}
]
},
{
$set: {
active_lock: {
lock_id: lock_id,
ts: now
}
}
}
);
if (res.modifiedCount === 0) {
return null;
}
return lock_id;
}
protected async releaseHandle(lock_id: bson.ObjectId) {
const res = await this.collection.updateOne(
{
'active_lock.lock_id': lock_id
},
{
$unset: {
active_lock: true
}
}
);
if (res.modifiedCount === 0) {
throw new Error('Lock not found, could not release');
}
}
}