| 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343 |
1
50
1
138
60
58
2
78
78
9
9
69
5
64
35
35
1
59
60
10
59
56
56
43
97
28
1
14
14
14
14
14
1
24
24
20
20
3
3
7
134
508
499
508
134
18
18
14
4
4
4
8
8
8
4
5
5
5
5
26
26
26
19
22
22
6
1
1
1
1
9
9
9
9
1
1
1
3
3
3
3
2
2
2
4
4
4
2
2
4
4
4
2
2
2
4
2
2
2
2
2
2
2
9
9
9
9
7
9
9
1
24
4
11
| /*
* Copyright 2014-2016, Sébastien Piquemal <sebpiq@gmail.com>
*
* rhizome is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* rhizome is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with rhizome. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
var path = require('path')
, fs = require('fs')
, EventEmitter = require('events').EventEmitter
, async = require('async')
, _ = require('underscore')
, nedb = require('nedb')
, redis = require('redis')
, errors = require('../core/errors')
, utils = require('../core/utils')
// Store that does not store the data
var BaseStore = exports.BaseStore = function() { EventEmitter.apply(this) }
_.extend(BaseStore.prototype, EventEmitter.prototype, {
// --------------- Methods to implement
// Starts the persistence store
start: function(done) { throw Error('implement me') },
// Stops the persistence store
stop: function(done) { throw Error('implement me') },
// Fetches all the connections ids in `namespace` and calls `done(err, ids)`.
connectionIdList: function(namespace, done) { throw Error('implement me') },
// Restores the persisted state of the manager, and calls `done(err, state)`.
// `state` is `null` if it was not previously saved.
managerRestore: function(done) { throw Error('implement me') },
// Saves the manager `state` and calls `done(err)`.
managerSave: function(state, done) { throw Error('implement me') },
// Assigns a unique id to the connection and calls `done`
_connectionAssignUniqueId: function(connection, done) { throw Error('implement me') },
// Returns the data as used by connection.serialize() / deserialize() or `null`
_connectionGet: function(connection, done) { throw Error('implement me') },
_connectionInsert: function(connection, done) { throw Error('implement me') },
_connectionUpdate: function(connection, done) { throw Error('implement me') },
// --------------- Other public methods
// Inserts or restores the connection and calls `done(err)`
connectionInsertOrRestore: function(connection, done) {
if (connection.id === null) {
// If connection id is null (autoId is true), generate a new unique id
if (connection.autoId === true) {
async.series([
this._connectionAssignUniqueId.bind(this, connection),
this._connectionInsert.bind(this, connection)
], done)
}
// Rejects connections with no id, if autoId is false
else
return done(new Error('if autoId is false, connection.id must be set'))
// If connection already has an id assigned, we don't know whether it is new
// and we need to insert it, or whether it should be restored
} else {
this._connectionGet(connection, (err, data) => {
// Connection exists, so we just restore it
if (data) {
connection.deserialize(data)
return done(null, connection)
// Connection doesn't exist, and its autoId is set to true, we force a new id
// so we ignore the original connection id.
} else if (connection.autoId === true) {
async.series([
this._connectionAssignUniqueId.bind(this, connection),
this._connectionInsert.bind(this, connection)
], done)
// ??? } else next(new Error('could not restore connection and autoId is False'))
// Connection doesn't exist and it has an id already assigned,
// so we simply insert it.
} else this._connectionInsert(connection, done)
})
}
},
// Updates an already existing connection,
connectionUpdate: function(connection, done) { this._connectionUpdate(connection, done) }
})
// Store that does not store the data
var NoStore = exports.NoStore = function() { BaseStore.apply(this, arguments) }
_.extend(NoStore.prototype, BaseStore.prototype, {
start: function(done) { done() },
stop: function(done) { done() },
connectionIdList: function(namespace, done) { done(null, []) },
managerRestore: function(done) { done(null, null) },
managerSave: function(state, done) { done() },
_connectionAssignUniqueId: function(connection, done) {
connection.id = Math.random().toString().slice(2)
done()
},
_connectionGet: function(connection, done) { done(null, null) },
_connectionInsert: function(connection, done) { done() },
_connectionUpdate: function(connection, done) { done() }
})
// Creates a nedb persistance store. `dbDir` is the absolute path
// of the folder where the db files will be stored.
// !!! This does not support concurrent read/write from several node processes.
var NEDBStore = exports.NEDBStore = function(dbDir) {
BaseStore.apply(this)
this._connectionsCollection = null
this._dbDir = dbDir
this._collectionFile = path.join(dbDir, 'connections.db')
this._managerFile = path.join(dbDir, 'manager.json')
}
_.extend(NEDBStore.prototype, BaseStore.prototype, {
start: function(done) {
this._connectionsCollection = new nedb({ filename: this._collectionFile })
async.series([
this._connectionsCollection.loadDatabase.bind(this._connectionsCollection)
], done)
},
stop: function(done) {
this._connectionsCollection = null
done()
},
connectionIdList: function(namespace, done) {
this._connectionsCollection.find({ namespace: namespace }, (err, docs) => {
Iif (err) return done(err)
done(null, docs.map((doc) => doc.connectionId))
})
},
managerSave: function(state, done) {
// Remove Buffers from `state` as we cannot serialize them to JSON.
state.nsTree = state.nsTree.map((nodeData) => {
if (nodeData.lastMessage)
nodeData.lastMessage = nodeData.lastMessage.map((arg) => (arg instanceof Buffer) ? null : arg)
return nodeData
})
fs.writeFile(this._managerFile, JSON.stringify(state), done)
},
managerRestore: function(done) {
fs.readFile(this._managerFile, (err, state) => {
if (err) {
Eif (err.code === 'ENOENT') done(null, null)
else done(err)
} else {
state = JSON.parse(state)
_.defaults(state, { nsTree: [] })
state.nsTree = state.nsTree.map((nodeData) => {
if (nodeData.lastMessage)
nodeData.lastMessage = nodeData.lastMessage.map((arg) => (arg === null) ? new Buffer('') : arg)
return nodeData
})
done(null, state)
}
})
},
_connectionAssignUniqueId: function(connection, done) {
this._connectionsCollection.insert({}, (err, doc) => {
Iif (err) return done(err)
connection.id = doc._id
done(null)
})
},
_connectionGet: function(connection, done) {
this._connectionsCollection.findOne({
connectionId: connection.id,
namespace: connection.namespace
}, (err, doc) => {
Iif (err) done(err)
else if (doc) done(null, doc.data)
else done(null, null)
})
},
_connectionInsert: function(connection, done) {
var doc = {
connectionId: connection.id,
namespace: connection.namespace,
data: connection.serialize()
}
this._connectionsCollection.insert(doc, done)
},
_connectionUpdate: function(connection, done) {
this._connectionsCollection.update(
{ connectionId: connection.id, namespace: connection.namespace },
{ '$set': { data: connection.serialize() }
}, done)
}
})
// Creates a redis persistence store.
var RedisStore = exports.RedisStore = function() {
BaseStore.apply(this)
this._redisClient = null
}
_.extend(RedisStore.prototype, NoStore.prototype, {
// --------------- Implemented methods
start: function(done) {
this._redisClient = this._createClient()
this._redisClient.once('ready', () => done())
this._redisClient.on('reconnecting', () => console.log(this, 'reconnecting ...'))
this._redisClient.on('error', (err) => this.emit('error', err))
},
stop: function(done) {
this._redisClient.once('end', () => {
this._redisClient.removeAllListeners()
this._redisClient.on('error', () => {})
this._redisClient = null
done()
})
this._redisClient.quit()
},
connectionIdList: function(namespace, done) {
var keyBase = 'connections:' + namespace + ':'
this._redisClient.keys(keyBase + '*', (err, keys) => {
Iif (err) return done(err)
done(null, keys.map((key) => key.replace(keyBase, '')))
})
},
managerRestore: function(done) {
this._redisClient.get('manager', (err, value) => {
Iif (err) return done(err)
if (!value) return done(null, null)
else {
var state = this._parseValue(value)
_.defaults(state, { nsTree: [] })
state.nsTree = state.nsTree.map((nodeData) => {
if (nodeData.lastMessage)
nodeData.lastMessage = nodeData.lastMessage.map((arg) => (arg === null) ? new Buffer('') : arg)
return nodeData
})
done(null, state)
}
})
},
managerSave: function(state, done) {
state.nsTree = state.nsTree.map((nodeData) => {
if (nodeData.lastMessage)
nodeData.lastMessage = nodeData.lastMessage.map((arg) => (arg instanceof Buffer) ? null : arg)
return nodeData
})
this._redisClient.set('manager', this._stringifyValue(state), (err) => done(err))
},
_connectionAssignUniqueId: function(connection, done) {
connection.id = null
async.whilst(
() => !connection.id,
(nextKey) => {
var redisKey
connection.id = utils.getRandomString(8)
redisKey = this._makeKey(connection)
// Try to set the key `redisKey`, because we use option 'nx,
// setting will fail and `null` be returned if the key already exists.
this._redisClient.set(redisKey, '', 'nx', (err, reply) => {
Iif (err) return done(err)
else Iif (reply === null)
connection.id = null
nextKey()
})
},
done
)
},
_connectionGet: function(connection, done) {
var redisKey = this._makeKey(connection)
this._redisClient.get(redisKey, (err, value) => {
Iif (err) return done(err)
else if (value && value.length) done(null, this._parseValue(value))
// If `value` exists, but is an empty string, we consider the entry doesn't exist
else done(null, null)
})
},
_connectionInsert: function(connection, done) {
var redisKey = this._makeKey(connection)
this._redisClient.set(redisKey, this._stringifyValue(connection.serialize()), done)
},
_connectionUpdate: function(connection, done) { this._connectionInsert(connection, done) },
// --------------- Other helpers
_createClient: function() {
return redis.createClient()
},
_makeKey: function(connection) {
return 'connections:' + connection.namespace + ':' + connection.id
},
_parseValue: function(value) {
return JSON.parse(value)
},
_stringifyValue: function(value) {
return JSON.stringify(value)
}
}) |