-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
218 lines (188 loc) · 6.45 KB
/
index.js
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
var _ = require('lodash');
var crypto = require('crypto');
var debug = require('debug')('lock');
var marshal = require('@momsfriendlydevco/marshal');
var mongoose = require('mongoose');
var lock = function(options) {
this.settings = {
...lock.defaults,
...options,
};
this.schema; // Mongo schema when database connection completes
this.model; // Mongo model when above completes
/**
* Set one or more settings
* @param {string|Object} key A single key to set or an object to merge, dotted notation supported
* @returns {Lock} This chainable instance
*/
this.set = (key, val) => {
if (!key) {
// Pass
} else if (_.isString(key)) {
_.set(this.settings, key, val);
} else {
_.merge(this.settings, key);
}
return this;
};
/**
* Verify settings and connect to database
* @param {Object} [settings] Optional settings object
* @returns {Promise} A promise which will resolve when complete
*/
this.init = settings => Promise.resolve()
.then(()=> this.set(settings))
// Sanity checks {{{
.then(()=> {
['mongodb.uri', 'mongodb.collection']
.forEach(key => {
if (!_.has(this.settings, key)) throw new Error(`Missing setting: ${key}`);
});
})
// }}}
.then(()=> mongoose.set('useFindAndModify', false))
.then(()=> mongoose.set('useCreateIndex', true))
.then(()=> mongoose.createConnection(this.settings.mongodb.uri, this.settings.mongodb.options))
.then(()=> this.schema = new mongoose.Schema({
key: {type: mongoose.Schema.Types.String, index: {unique: true}},
expiry: {type: mongoose.Schema.Types.Date},
ttl: {type: mongoose.Schema.Types.Date},
created: {type: mongoose.Schema.Types.Date},
}, {strict: false}))
.then(()=> this.model = mongoose.model(this.settings.mongodb.collection, this.schema));
/**
* Retrieve lock data
* @param {*} key The key to retrieve
* @returns {Promise <Object>} The lock data, this includes the original key and additional fields attached to it. If no lock is found this returns undefined
*/
this.get = key => Promise.resolve()
.then(()=> key = this.hash(key))
.then(()=> this.model.findOne({key}).lean())
.then(doc => _.omit(doc, this.settings.omitFields))
/**
* Request if a lock exists
* @param {*} key The key to check, if a non-string this is run via hash() first
* @returns {Promise <boolean>} A promise which will resolve with a boolean indicating if the lock exists
*/
this.exists = key => Promise.resolve()
.then(()=> key = this.hash(key))
// TODO: This could more simply call `clean()` first and query by `key`
.then(()=> this.model.findOne({
key: {$eq: key},
expiry: {$gt: new Date()},
ttl: {$gt: new Date()},
}).select('_id').lean())
.then(doc => {
var exists = !!doc;
debug('Check key exists', key, '?', exists);
return exists;
});
/**
* Attempt to create a lock, returning a boolean for success
* @param {*} key The key to lock, hashed if necessary via hash()
* @param {Object} fields Additional fields to pass, can contain `{created, expiry}`
* @returns {Promise <boolean>} A promise which will resolve with true/false if the lock was created
*/
this.create = (key, fields) => Promise.resolve()
.then(()=> this.clean()) // We must remove expired records to avoid unique key conflicts
.then(()=> this.hash(key))
.then(keyHash => { debug('Create lock with key', keyHash); return keyHash })
.then(keyHash => this.model.create({
key: keyHash,
created: new Date(),
expiry: new Date(Date.now()+this.settings.expiry),
ttl: new Date(Date.now()+this.settings.ttl),
...fields,
// Legacy expansion into main lock object
...(this.settings.includeKeys && _.isObject(key) ? key : undefined),
// Additional meta key to retain reserved keys like `id`
meta: {...(this.settings.includeKeys && _.isObject(key) ? key : undefined)}
}))
.then(()=> {
debug('Key created', key);
return true;
})
.catch(e => {
debug('Error creating key', key, e);
return false;
});
/**
* Update the data behind an existing lock
* @param {*} key The key to lock, hashed if necessary via hash()
* @param {Object} fields Fields to update, can contain `{created, expiry}`
* @returns {Promise} A promise which will resolve with the updated lock
*/
this.update = (key, fields) => Promise.resolve()
.then(()=> key = this.hash(key))
.then(()=> this.model.updateOne({key}, fields));
/**
* Release a lock
* @param {*} key The key to release, hashed if neccessary via hash()
* @returns {Promise <boolean>} A promise which will resolve when the lock has been removed with a boolean indicating whether the lock existed
*/
this.release = key => Promise.resolve()
.then(()=> key = this.hash(key))
.then(()=> this.model.deleteOne({key}))
.then(()=> true)
.catch(()=> false);
/**
* Remove all expired locks from the database
* @returns {Promise} A promise which will resolve when the cleaning has completed
*/
// FIXME: This is an OR?
this.clean = ()=> this.model.deleteMany({
$or: [
{expiry: {$lt: new Date()}},
{ttl: {$lt: new Date()}},
]
});
/**
* Remove ALL locks from the database
* This is only really useful when debugging
* @returns {Promise} A promise which will resolve when the clearing has completed
*/
this.clear = ()=> this.model.deleteMany();
/**
* Keep-alive
* Updates time-to-live so that disconnected clients can be detected
* @param {*} key The key to hash
* @returns {Promise} A promise which will resolve with the updated lock
*/
this.alive = key => Promise.resolve()
.then(()=> key = this.hash(key))
.then(()=> this.model.updateOne({key}, {ttl: new Date(Date.now()+this.settings.ttl)}));
/**
* Return a string varient of a complex object
* If passed a string this returns the same value, for everything else an SHA-256 hash is used instead
* @param {*} key The key to hash
* @returns {string} A hash of the input key
*/
this.hash = key =>
_.isString(key)
? key
: crypto.createHash('sha256')
.update(marshal.serialize(key, {symetric: true}))
.digest('hex')
/**
* Close the module and release the database connection
* @returns {Promise} A promise which will resolve when the connection has been released
*/
this.destroy = ()=> this.model
? mongoose.connection.close()
: Promise.resolve();
return this;
};
lock.defaults = {
expiry: 1000 * 60 * 60, // 1 hour
ttl: 1000 * 60 * 1, // 1 min
mongodb: {
uri: 'mongodb://localhost/mfdc-cache',
collection: 'locks',
options: {
useNewUrlParser: true,
},
},
omitFields: ['_id', '__v'],
includeKeys: true,
};
module.exports = lock;