-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.js
343 lines (309 loc) · 10.1 KB
/
router.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
const debug = require('debug')('traffic:router')
const redis = require('redis')
const Redlock = require('redlock')
const dynamoose = require('dynamoose')
const xmpp = require('node-xmpp-core')
const EventEmitter = require('events')
const junction = require('junction')
const pjson = require('./package.json')
const os = require('os')
const markerLocal = '!'
const markerRemote = '^'
function Router (opts = {}) {
this.opts = opts
this.router = opts.router
this.log = opts.log.child({ module: 'router' })
this.region = opts.region
if (process.env.NODE_ENV === 'development') {
if (!this.region) this.region = 'local'
dynamoose.local(opts.dynamo || 'http://localhost:' + 4567)
}
dynamoose.AWS.config.update({ region: this.region })
this.dumpExceptions = opts.dumpExceptions != null
? opts.dumpExceptions
: true
this.db = opts.db || 0
this.prefix = opts.prefix ? opts.prefix + '/' : undefined
this.redis = opts.redis ||
redis.createClient({ db: this.db, prefix: this.prefix })
this.redsub = opts.redsub || this.redis.duplicate()
this.redlock = new Redlock([this.redis], { retryCount: 0 })
this.redis.on('error', err => this.log.error(err))
this.redlock.on('clientError', err => this.log.error(err))
// pass as Session and Direct store
require('./models/session').setStore(this.redis)
require('./models/direct').setStore(this.redis)
// route messaging
this._channelEmitter = new EventEmitter().setMaxListeners(0)
this.redsub.on('message', this.onMessage.bind(this))
// queue messaging
this.queueLock = 3000
this.queueChannel = `__keyevent@${this.redsub.options.db}__:lpush`
this.redsub.config('SET', 'notify-keyspace-events', 'El')
this.redsub.subscribe(this.queueChannel)
// process packet to server
var server = (this.server = junction())
if (process.env.DEBUG) {
server.use(
require('./modules/logger')({ prefix: 'SERVER: ', logger: debug })
)
}
server
.use(require('junction-lastactivity')())
.use(require('junction-ping')())
.use(
require('junction-softwareversion')(pjson.name, pjson.version, Router.os)
)
.use(require('junction-time')())
.use(
junction.middleware.serviceDiscovery(
[{ category: 'server', type: 'im' }],
[
'http://jabber.org/protocol/disco#info',
// 'http://jabber.org/protocol/disco#items', // FIXME
'jabber:iq:last',
'urn:xmpp:ping',
'jabber:iq:version',
'urn:xmpp:time'
]
)
)
server
.use(junction.serviceUnavailable())
.use(junction.errorHandler({ dumpExceptions: this.dumpExceptions }))
// process packet to client
var user = (this.user = junction())
if (process.env.DEBUG) {
user.use(require('./modules/logger')({ prefix: 'USER: ', logger: debug }))
}
user
.use(require('./modules/roster')(this))
.use(require('junction-lastactivity')())
.use(require('./modules/subscription')(this))
.use(require('./modules/presence')(this))
.use(require('./modules/deliver')(this))
user
.use(junction.serviceUnavailable())
.use(junction.errorHandler({ dumpExceptions: this.dumpExceptions }))
// packet from c2s to the world
var outbound = (this.outbound = junction())
if (process.env.DEBUG) {
outbound.use(
require('./modules/logger')({ prefix: 'FROM: ', logger: debug })
)
}
var route = (stanza, next) => this.process(stanza)
outbound
.use(require('./modules/subscription').outbound(this))
.use(require('./modules/presence').outbound(this))
.use(route)
.use(junction.errorHandler({ dumpExceptions: this.dumpExceptions }))
// packet to c2s
var deliver = (this.deliver = junction())
if (process.env.DEBUG) {
deliver.use(require('./modules/logger')({ prefix: 'TO: ', logger: debug }))
}
var send = (stanza, next) => this.route(stanza.to, stanza)
deliver
.use(require('./modules/presence').deliver(this))
.use(send)
.use(junction.errorHandler({ dumpExceptions: this.dumpExceptions }))
}
Router.os = `${process.release.name}/${process.release.lts || process.versions.node.split('.')[0]} (${os.type()} ${os.arch()})`
module.exports = Router
/* Push stanza to directly connected client(s)
*/
Router.prototype.route = function (jid, stanza) {
if (!jid) {
throw new Error('Route jid required')
}
debug('route %s %s', jid, stanza)
this.redis.publish('route:' + jid, stanza.toString())
}
Router.prototype.registerRoute = function (jid, client) {
if (!client || !client.id) {
throw new Error('Invalid client to subscribe')
}
var channel = 'route:' + jid
var listener = packet => {
debug('got packet', packet)
client.send(xmpp.parse(packet))
}
listener.client = client
this._channelEmitter.addListener(channel, listener)
this.redsub.subscribe(channel, (err, reply) => {
if (err) throw err
// TODO: Analyze this
debug('registered route %s -> %s', jid, client.id)
})
}
Router.prototype.unregisterRoute = function (jid, client) {
if (!client || !client.id) {
throw new Error('Invalid client to unsubscribe')
}
var channel = 'route:' + jid
var listener = this._channelEmitter
.listeners(channel)
.find(listener => listener.client === client)
if (!listener) {
// FIXME: throw new Error(`No listener for ${client.id} on ${channel}`)
return
}
this._channelEmitter.removeListener(channel, listener)
this.redsub.unsubscribe(channel, (err, reply) => {
if (err) throw err
// TODO: Analyze this
debug('unregistered route %s -> %s', jid, client.id)
})
}
/* Enqueue delivery to JID
*/
Router.prototype.queue = function (local, jid, stanza) {
if (!jid) {
throw new Error('Queue jid required')
}
debug('queue %s %s', jid, stanza)
this.redis.lpush(
'queue:' + jid,
(local ? markerLocal : markerRemote) + stanza.toString(),
function (err, res) {
if (err) this.log.error({ err }, 'queue %s', jid)
}
)
}
Router.prototype.onMessage = function (channel, message) {
debug('message', channel, message)
if (channel.startsWith('__')) {
// keyspace notification
const prefix = this.prefix || ''
if (channel === this.queueChannel && message.startsWith(prefix)) {
const name = message.substr(`${prefix}queue:`.length)
const jid = new xmpp.JID(name)
const queue = `queue:${name}`
const lock = `${prefix}lock:${name}`
if (!jid) {
throw new Error(`Cannot handle ${queue}`)
}
const processQueue = lock => {
this.redis.rpop(queue, (err, stanza) => {
if (err) {
this.log.error({ err }, 'queue %s', queue)
}
if (!err && stanza) {
const local = stanza[0] === markerLocal
stanza = stanza.slice(1)
this.dispatch(local, jid, stanza)
// extend lock and process next queue stanza
// if failed to extend, this means that someone else is processing
// the queue already, so we are ok with this
lock.extend(this.queueLock).then(processQueue)
} else {
lock.unlock().catch(err => {
// we weren't able to reach redis; your lock will eventually expire
this.log.error({ err }, 'queue %s unlock error', queue)
})
}
})
}
this.redlock.lock(lock, this.queueLock).then(processQueue).catch(err => {
// ignore resource unavailable error - this is expected
if (!(err instanceof Redlock.LockError)) {
this.log.error({ err }, 'queue %s lock error', queue)
}
})
}
} else {
// stanza routing
this._channelEmitter.emit(channel, message)
}
}
/* Build iq-response for iq-get or iq-set stanza
*/
Router.prototype.makeResponse = function (from, stanza) {
return new xmpp.Stanza(stanza.name, {
id: stanza.attrs.id,
from: from.toString(),
to: stanza.attrs.from,
type: stanza.is('iq') ? 'result' : null
})
}
/* Dispatch stanza coming from queue to other queues/routes
*/
Router.prototype.dispatch = function (local, jid, packet) {
debug('dispatch %s', jid, packet)
const stanza = xmpp.parse(packet)
if (!stanza) {
throw new Error(`Failed to dispatch: ${packet}`)
}
if (local) {
const router = this
stanza.to = jid.toString()
stanza.send = stanza => {
router.process(stanza)
}
const response = this.makeResponse(jid, stanza)
response.send = () => {
router.process(response)
}
if (jid.local) {
// to user
if (jid.resource) {
this.deliver.handle(stanza, response, err => {
if (err) this.log.error(err)
})
} else {
this.user.handle(stanza, response, err => {
if (err) this.log.error(err)
})
}
} else {
this.server.handle(stanza, response, err => {
if (err) this.log.error(err)
})
}
} else {
if (jid.local || jid.resource) {
this.queue(local, jid.domain, stanza)
} else {
// pass to s2s router
if (stanza.attrs.xmlns === 'jabber:client') {
stanza.attrs.xmlns = 'jabber:server'
}
this.router.send(stanza)
}
}
}
/* handle c2s outbound stanza
*/
Router.prototype.handle = function (client, stanza) {
debug('handle %s', stanza)
stanza.client = client
stanza.send = stanza => {
this.process(stanza)
}
const response = this.makeResponse(client.jid.bare(), stanza)
response.send = () => {
client.send(response)
}
this.outbound.handle(stanza, response, err => {
if (err) {
this.log.error({ client_id: client.id, client_jid: client.jid, err })
}
})
}
/* Process server inbound stanza (from c2s, s2s or internally generated)
*/
Router.prototype.process = function (stanza, local) {
debug('process %s', stanza, local)
if (!stanza || !stanza.attrs) {
throw new Error('Need stanza to process')
}
// http://xmpp.org/rfcs/rfc6120.html#stanzas-attributes-to-c2s
// s2s packets was already checked for proper to/from
const to = stanza.attrs.to
? new xmpp.JID(stanza.attrs.to)
: new xmpp.JID(stanza.attrs.from).bare()
const from = new xmpp.JID(stanza.attrs.from)
local = local != null ? local : to.domain === from.domain
this.queue(local, to, stanza)
}