forked from moscajs/aedes-persistence-redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpersistence.js
638 lines (526 loc) · 15.4 KB
/
persistence.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
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
'use strict'
const Redis = require('ioredis')
const from = require('from2')
const through = require('through2')
const throughv = require('throughv')
const msgpack = require('msgpack-lite')
const pump = require('pump')
const CachedPersistence = require('aedes-cached-persistence')
const Packet = CachedPersistence.Packet
const inherits = require('util').inherits
const HLRU = require('hashlru')
const QlobberTrue = require('qlobber').QlobberTrue
const qlobberOpts = {
separator: '/',
wildcard_one: '+',
wildcard_some: '#',
match_empty_levels: true
}
const clientKey = 'client:'
const clientsKey = 'clients'
const willsKey = 'will'
const willKey = 'will:'
const retainedKey = 'retained'
const outgoingKey = 'outgoing:'
const outgoingIdKey = 'outgoing-id:'
const incomingKey = 'incoming:'
function RedisPersistence (opts) {
if (!(this instanceof RedisPersistence)) {
return new RedisPersistence(opts)
}
opts = opts || {}
this.maxSessionDelivery = opts.maxSessionDelivery || 1000
this.packetTTL = opts.packetTTL || function () { return 0 }
this.messageIdCache = HLRU(100000)
if (opts.cluster) {
this._db = new Redis.Cluster(opts.cluster)
} else {
this._db = opts.conn || new Redis(opts)
}
this._getRetainedChunkBound = this._getRetainedChunk.bind(this)
CachedPersistence.call(this, opts)
}
inherits(RedisPersistence, CachedPersistence)
RedisPersistence.prototype.storeRetained = function (packet, cb) {
if (packet.payload.length === 0) {
this._db.hdel(retainedKey, packet.topic, cb)
} else {
this._db.hset(retainedKey, packet.topic, msgpack.encode(packet), cb)
}
}
RedisPersistence.prototype._getRetainedChunk = function (chunk, enc, cb) {
this._db.hgetBuffer(retainedKey, chunk, cb)
}
RedisPersistence.prototype.createRetainedStreamCombi = function (patterns) {
var that = this
var qlobber = new QlobberTrue(qlobberOpts)
for (var i = 0; i < patterns.length; i++) {
qlobber.add(patterns[i])
}
var stream = through.obj(that._getRetainedChunkBound)
this._db.hkeys(retainedKey, function getKeys (err, keys) {
if (err) {
stream.emit('error', err)
} else {
matchRetained(stream, keys, qlobber)
}
})
return pump(stream, throughv.obj(decodeRetainedPacket))
}
RedisPersistence.prototype.createRetainedStream = function (pattern) {
return this.createRetainedStreamCombi([pattern])
}
function matchRetained (stream, keys, qlobber) {
for (var i = 0, l = keys.length; i < l; i++) {
if (qlobber.test(keys[i])) {
stream.write(keys[i])
}
}
stream.end()
}
function decodeRetainedPacket (chunk, enc, cb) {
cb(null, msgpack.decode(chunk))
}
RedisPersistence.prototype.addSubscriptions = function (client, subs, cb) {
if (!this.ready) {
this.once('ready', this.addSubscriptions.bind(this, client, subs, cb))
return
}
var clientSubKey = clientKey + client.id
var toStore = {}
var published = 0
var errored
for (var i = 0; i < subs.length; i++) {
var sub = subs[i]
toStore[sub.topic] = sub.qos
}
this._db.sadd(clientsKey, client.id, finish)
this._db.hmset(clientSubKey, toStore, finish)
this._addedSubscriptions(client, subs, finish)
function finish (err) {
errored = err
published++
if (published === 3) {
cb(errored, client)
}
}
}
RedisPersistence.prototype.removeSubscriptions = function (client, subs, cb) {
if (!this.ready) {
this.once('ready', this.removeSubscriptions.bind(this, client, subs, cb))
return
}
var clientSubKey = clientKey + client.id
var errored = false
var outstanding = 0
function check (err) {
if (err) {
if (!errored) {
errored = true
cb(err)
}
}
if (errored) {
return
}
outstanding--
if (outstanding === 0) {
cb(null, client)
}
}
var that = this
this._db.hdel(clientSubKey, subs, function subKeysRemoved (err) {
if (err) {
return cb(err)
}
outstanding++
that._db.exists(clientSubKey, function checkAllSubsRemoved (err, subCount) {
if (err) {
return check(err)
}
if (subCount === 0) {
outstanding++
that._db.del(outgoingKey + client.id, check)
return that._db.srem(clientsKey, client.id, check)
}
check()
})
outstanding++
that._removedSubscriptions(client, subs.map(toSub), check)
})
}
function toSub (topic) {
return {
topic: topic
}
}
RedisPersistence.prototype.subscriptionsByClient = function (client, cb) {
var clientSubKey = clientKey + client.id
this._db.hgetall(clientSubKey, function returnSubs (err, subs) {
var toReturn = returnSubsForClient(subs)
cb(err, toReturn.length > 0 ? toReturn : null, client)
})
}
function returnSubsForClient (subs) {
var subKeys = Object.keys(subs)
var toReturn = []
if (subKeys.length === 0) {
return toReturn
}
for (var i = 0; i < subKeys.length; i++) {
toReturn.push({
topic: subKeys[i],
qos: parseInt(subs[subKeys[i]])
})
}
return toReturn
}
RedisPersistence.prototype.countOffline = function (cb) {
var that = this
this._db.scard(clientsKey, function countOfflineClients (err, count) {
if (err) {
return cb(err)
}
cb(null, that._trie.subscriptionsCount, parseInt(count) || 0)
})
}
RedisPersistence.prototype.subscriptionsByTopic = function (topic, cb) {
if (!this.ready) {
this.once('ready', this.subscriptionsByTopic.bind(this, topic, cb))
return this
}
var result = this._trie.match(topic)
cb(null, result)
}
RedisPersistence.prototype._setup = function () {
if (this.ready) {
return
}
var that = this
var hgetallStream = throughv.obj(function getStream (clientId, enc, cb) {
var clientSubKey = clientKey + clientId
that._db.hgetall(clientSubKey, function clientHash (err, hash) {
cb(err, { clientHash: hash, clientId: clientId })
})
}, function emitReady (cb) {
that.ready = true
that.emit('ready')
cb()
}).on('data', function processKeys (data) {
processKeysForClient(data.clientId, data.clientHash, that)
})
this._db.smembers(clientsKey, function smembers (err, clientIds) {
if (err) {
hgetallStream.emit('error', err)
} else {
for (var i = 0, l = clientIds.length; i < l; i++) {
hgetallStream.write(clientIds[i])
}
hgetallStream.end()
}
})
}
function processKeysForClient (clientId, clientHash, that) {
var topics = Object.keys(clientHash)
for (var i = 0; i < topics.length; i++) {
var topic = topics[i]
that._trie.add(topic, {
clientId: clientId,
topic: topic,
qos: clientHash[topic]
})
}
}
RedisPersistence.prototype.outgoingEnqueue = function (sub, packet, cb) {
this.outgoingEnqueueCombi([sub], packet, cb)
}
RedisPersistence.prototype.outgoingEnqueueCombi = function (subs, packet, cb) {
if (!subs || subs.length === 0) {
return cb(null, packet)
}
var count = 0
var outstanding = 1
var errored = false
var packetKey = 'packet:' + packet.brokerId + ':' + packet.brokerCounter
var countKey = 'packet:' + packet.brokerId + ':' + packet.brokerCounter + ':offlineCount'
var ttl = this.packetTTL(packet)
var encoded = msgpack.encode(new Packet(packet))
this._db.mset(packetKey, encoded, countKey, subs.length, finish)
if (ttl > 0) {
outstanding += 2
this._db.expire(packetKey, ttl, finish)
this._db.expire(countKey, ttl, finish)
}
for (var i = 0; i < subs.length; i++) {
var listKey = outgoingKey + subs[i].clientId
this._db.rpush(listKey, packetKey, finish)
}
function finish (err) {
count++
if (err) {
errored = err
return cb(err)
}
if (count === (subs.length + outstanding) && !errored) {
cb(null, packet)
}
}
}
function updateWithClientData (that, client, packet, cb) {
var messageIdKey = outgoingIdKey + client.id + ':' + packet.messageId
var clientListKey = outgoingKey + client.id
var packetKey = 'packet:' + packet.brokerId + ':' + packet.brokerCounter
if (packet.cmd && packet.cmd !== 'pubrel') { // qos=1
that.messageIdCache.set(messageIdKey, packetKey)
return that._db.set(packetKey, msgpack.encode(packet), function updatePacket (err, result) {
if (err) {
return cb(err, client, packet)
}
if (result !== 'OK') {
cb(new Error('no such packet'), client, packet)
} else {
cb(null, client, packet)
}
})
}
// qos=2
var clientUpdateKey = outgoingKey + client.id + ':' + packet.brokerId + ':' + packet.brokerCounter
that.messageIdCache.set(messageIdKey, clientUpdateKey)
var count = 0
that._db.lrem(clientListKey, 0, packetKey, function (err, removed) {
if (err) {
return cb(err)
}
if (removed === 1) {
that._db.rpush(clientListKey, clientUpdateKey, finish)
} else {
finish()
}
})
var ttl = that.packetTTL(packet)
var encoded = msgpack.encode(packet)
if (ttl > 0) {
that._db.set(clientUpdateKey, encoded, 'EX', ttl, setPostKey)
} else {
that._db.set(clientUpdateKey, encoded, setPostKey)
}
function setPostKey (err, result) {
if (err) {
return cb(err, client, packet)
}
if (result !== 'OK') {
cb(new Error('no such packet'), client, packet)
} else {
finish()
}
}
function finish (err) {
if (++count === 2) {
cb(err, client, packet)
}
}
}
function augmentWithBrokerData (that, client, packet, cb) {
var messageIdKey = outgoingIdKey + client.id + ':' + packet.messageId
var key = that.messageIdCache.get(messageIdKey)
if (!key) {
return cb(new Error('unknown key'))
}
var tokens = key.split(':')
packet.brokerId = tokens[tokens.length - 2]
packet.brokerCounter = tokens[tokens.length - 1]
cb(null)
}
RedisPersistence.prototype.outgoingUpdate = function (client, packet, cb) {
var that = this
if (packet.brokerId && packet.messageId) {
updateWithClientData(this, client, packet, cb)
} else {
augmentWithBrokerData(this, client, packet, function updateClient (err) {
if (err) { return cb(err, client, packet) }
updateWithClientData(that, client, packet, cb)
})
}
}
RedisPersistence.prototype.outgoingClearMessageId = function (client, packet, cb) {
var that = this
var clientListKey = outgoingKey + client.id
var messageIdKey = outgoingIdKey + client.id + ':' + packet.messageId
var clientKey = this.messageIdCache.get(messageIdKey)
this.messageIdCache.remove(messageIdKey)
if (!clientKey) {
return cb(null, packet)
}
var count = 0
var errored = false
// TODO can be cached in case of wildcard deliveries
this._db.getBuffer(clientKey, function clearMessageId (err, buf) {
if (err) {
errored = err
return cb(err)
}
if (buf) {
var origPacket = msgpack.decode(buf)
origPacket.messageId = packet.messageId
var packetKey = 'packet:' + origPacket.brokerId + ':' + origPacket.brokerCounter
var countKey = 'packet:' + origPacket.brokerId + ':' + origPacket.brokerCounter + ':offlineCount'
if (clientKey !== packetKey) { // qos=2
that._db.del(clientKey, finish)
} else {
finish()
}
} else {
finish()
}
that._db.lrem(clientListKey, 0, packetKey, finish)
that._db.decr(countKey, function (err, remained) {
if (err) {
errored = err
return cb(err)
}
if (remained === 0) {
that._db.del(packetKey, countKey, finish)
} else {
finish()
}
})
function finish (err) {
count++
if (err) {
errored = err
return cb(err)
}
if (count === 3 && !errored) {
cb(err, origPacket)
}
}
})
}
RedisPersistence.prototype.outgoingStream = function (client) {
var clientListKey = outgoingKey + client.id
var stream = throughv.obj(this._buildAugment(clientListKey))
this._db.lrange(clientListKey, 0, this.maxSessionDelivery, lrangeResult)
function lrangeResult (err, results) {
if (err) {
stream.emit('error', err)
} else {
for (var i = 0, l = results.length; i < l; i++) {
stream.write(results[i])
}
stream.end()
}
}
return stream
}
RedisPersistence.prototype.incomingStorePacket = function (client, packet, cb) {
var key = incomingKey + client.id + ':' + packet.messageId
var newp = new Packet(packet)
newp.messageId = packet.messageId
this._db.set(key, msgpack.encode(newp), cb)
}
RedisPersistence.prototype.incomingGetPacket = function (client, packet, cb) {
var key = incomingKey + client.id + ':' + packet.messageId
this._db.getBuffer(key, function decodeBuffer (err, buf) {
if (err) {
return cb(err)
}
if (!buf) {
return cb(new Error('no such packet'))
}
cb(null, msgpack.decode(buf), client)
})
}
RedisPersistence.prototype.incomingDelPacket = function (client, packet, cb) {
var key = incomingKey + client.id + ':' + packet.messageId
this._db.del(key, cb)
}
RedisPersistence.prototype.putWill = function (client, packet, cb) {
var key = willKey + this.broker.id + ':' + client.id
packet.clientId = client.id
packet.brokerId = this.broker.id
this._db.rpush(willsKey, key)
this._db.setBuffer(key, msgpack.encode(packet), encodeBuffer)
function encodeBuffer (err) {
cb(err, client)
}
}
RedisPersistence.prototype.getWill = function (client, cb) {
var key = willKey + this.broker.id + ':' + client.id
this._db.getBuffer(key, function getWillForClient (err, packet) {
if (err) { return cb(err) }
var result = null
if (packet) {
result = msgpack.decode(packet)
}
cb(null, result, client)
})
}
RedisPersistence.prototype.delWill = function (client, cb) {
var key = willKey + client.brokerId + ':' + client.id
var result = null
var that = this
this._db.lrem(willsKey, 0, key)
this._db.getBuffer(key, function getClientWill (err, packet) {
if (err) { return cb(err) }
if (packet) {
result = msgpack.decode(packet)
}
that._db.del(key, function deleteWill (err) {
cb(err, result, client)
})
})
}
RedisPersistence.prototype.streamWill = function (brokers) {
var stream = throughv.obj(this._buildAugment(willsKey))
this._db.lrange(willsKey, 0, 10000, streamWill)
function streamWill (err, results) {
if (err) {
stream.emit('error', err)
} else {
for (var i = 0, l = results.length; i < l; i++) {
if (!brokers || !brokers[results[i].split(':')[1]]) {
stream.write(results[i])
}
}
stream.end()
}
}
return stream
}
RedisPersistence.prototype.getClientList = function (topic) {
var entries = this._trie.match(topic, topic)
function pushClientList (size, next) {
if (entries.length === 0) {
return next(null, null)
}
var chunk = entries.slice(0, 1)
entries = entries.slice(1)
next(null, chunk[0].clientId)
}
return from.obj(pushClientList)
}
RedisPersistence.prototype._buildAugment = function (listKey) {
var that = this
return function decodeAndAugment (key, enc, cb) {
that._db.getBuffer(key, function decodeMessage (err, result) {
var decoded
if (result) {
decoded = msgpack.decode(result)
}
if (err || !decoded) {
that._db.lrem(listKey, 0, key)
}
cb(err, decoded)
})
}
}
RedisPersistence.prototype.destroy = function (cb) {
var that = this
CachedPersistence.prototype.destroy.call(this, function disconnect () {
that._db.disconnect()
if (cb) {
that._db.on('end', cb)
}
})
}
module.exports = RedisPersistence