-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.js
304 lines (271 loc) · 7.64 KB
/
channel.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
const EventEmitter = require('events')
const noop = function () {}
class Channel extends EventEmitter {
/**
* Channel constructor.
*
* @param {Connection} connection
* @param {String} [name] optional channel/collection name, default is 'mubsub'
* @param {Object} [options] optional options
* - `size` max size of the collection in bytes, default is 5mb
* - `max` max amount of documents in the collection
* - `retryInterval` time in ms to wait if no docs found, default is 200ms
* - `recreate` recreate the tailable cursor on error, default is true
* @api public
*/
constructor (connection, name, options) {
super()
options || (options = {})
this.options = {
recreate: typeof options.recreate === 'boolean' ? options.recreate : true,
retryInterval:
typeof options.retryInterval === 'number' ? options.retryInterval : 200
}
this.collectionOpts = {
capped: true,
size: options.size || 1024 * 1024 * 5,
max: options.max
}
this.connection = connection
this.closed = false
this.listening = null
this.name = name || 'mubsub'
this.create().listen()
this.setMaxListeners(0)
}
/**
* Close the channel.
*
* @return {Channel} this
* @api public
*/
close () {
this.closed = true
return this
}
/**
* Publish an event.
*
* @param {String} event
* @param {Object} [message]
* @param {Function} [callback]
* @return {Channel} this
* @api public
*/
publish (event, message, callback) {
const options = callback ? { safe: true } : {}
callback || (callback = noop)
this.ready(function (collection) {
collection
.insertOne({ event, message }, options)
.then((result) => {
callback(null, { _id: result.insertedId })
})
.catch((err) => {
callback(err)
})
})
return this
}
/**
* Subscribe an event.
*
* @param {String} [event] if no event passed - all events are subscribed.
* @param {Function} callback
* @return {Object} unsubscribe function
* @api public
*/
subscribe (event, callback) {
const self = this
if (typeof event === 'function') {
callback = event
event = 'message'
}
this.on(event, callback)
return {
unsubscribe: function () {
self.removeListener(event, callback)
}
}
}
/**
* Create a channel collection.
*
* @return {Channel} this
* @api private
*/
create () {
const self = this
function create () {
self.connection.db
.createCollection(self.name, self.collectionOpts)
.then((collection) => {
self.collection = collection
self.emit('collection', self.collection)
})
.catch((err) => {
const collectionExistsError =
err &&
(err.codeName === 'NamespaceExists' ||
err.message === 'collection already exists' ||
err.message.toLowerCase().includes('collection already exists') ||
err.message.match(/^a collection.+already exists$/) ||
err.message.match(/^Collection.+already exists\.$/))
if (collectionExistsError) {
const collection = self.connection.db.collection(self.name)
collection.isCapped().then((capped) => {
if (!capped) {
self.emit(
'error',
new Error(`${err.message}, but it's NOT capped.`)
)
} else {
self.collection = collection
self.emit('collection', self.collection)
}
})
} else if (err) {
self.emit('error', err)
}
})
}
this.connection.db ? create() : this.connection.once('connect', create)
return this
}
/**
* Create a listener which will emit events for subscribers.
* It will listen to any document with event property.
*
* @param {Object} [latest] latest document to start listening from
* @return {Channel} this
* @api private
*/
listen (latest) {
const self = this
this.latest(
latest,
this.handle(true, function (latest, collection) {
const cursor = collection.find(
{ _id: { $gt: latest._id } },
{
tailable: true,
awaitData: true,
timeout: false,
maxAwaitTimeMS: self.options.retryInterval
}
).hint({ $natural: 1 })
const next = self.handle(function (doc) {
// There is no document only if the cursor is closed by accident.
// F.e. if collection was dropped or connection died.
if (!doc) {
return setTimeout(function () {
self.emit('error', new Error('Mubsub: broken cursor.'))
if (self.options.recreate) {
self.create().listen(latest)
}
}, 1000)
}
latest = doc
if (doc.event) {
self.emit(doc.event, doc.message)
self.emit('message', doc.message)
}
self.emit('document', doc)
process.nextTick(more)
})
const more = function () {
cursor
.next()
.then((doc) => next(undefined, doc))
.catch((err) => next(err))
}
more()
self.listening = collection
self.emit('ready', collection)
})
)
return this
}
/**
* Get the latest document from the collection. Insert a dummy object in case
* the collection is empty, because otherwise we don't get a tailable cursor
* and need to poll in a loop.
*
* @param {Object} [latest] latest known document
* @param {Function} callback
* @return {Channel} this
* @api private
*/
latest (latest, callback) {
function onCollection (collection) {
const cursor = collection
.find(latest ? { _id: latest._id } : {}, { timeout: false })
.hint({ $natural: -1 })
.limit(1)
cursor
.next()
.then((doc) => {
if (doc) {
return callback(undefined, doc, collection)
}
collection
.insertOne({ dummy: true }, { safe: true })
.then((result) => {
callback(null, { _id: result.insertedId }, collection)
})
.catch((err) => {
callback(err, undefined, collection)
})
})
.catch((err) => {
callback(err, undefined, collection)
})
}
this.collection
? onCollection(this.collection)
: this.once('collection', onCollection)
return this
}
/**
* Return a function which will handle errors and consider channel and connection
* state.
*
* @param {Boolean} [exit] if error happens and exit is true, callback will not be called
* @param {Function} callback
* @return {Function}
* @api private
*/
handle (exit, callback) {
const self = this
if (typeof exit === 'function') {
callback = exit
exit = null
}
return function () {
if (self.closed || self.connection.destroyed) {
return
}
const args = [].slice.call(arguments)
const err = args.shift()
if (err) self.emit('error', err)
if (err && exit) return
callback.apply(self, args)
}
}
/**
* Call back if collection is ready for publishing.
*
* @param {Function} callback
* @return {Channel} this
* @api private
*/
ready (callback) {
if (this.listening) {
callback(this.listening)
} else {
this.once('ready', callback)
}
return this
}
}
module.exports = Channel