node-ldapjs/examples/cluster-threading.js

66 lines
1.5 KiB
JavaScript
Raw Normal View History

2021-05-27 19:16:05 +00:00
const cluster = require('cluster')
const ldap = require('ldapjs')
const os = require('os')
2021-05-27 19:16:05 +00:00
const threads = []
threads.getNext = function () {
2021-05-27 19:16:05 +00:00
return (Math.floor(Math.random() * this.length))
}
const serverOptions = {
2021-05-27 19:16:05 +00:00
connectionRouter: (socket) => {
socket.pause()
console.log('ldapjs client requesting connection')
const routeTo = threads.getNext()
threads[routeTo].send({ type: 'connection' }, socket)
}
}
2021-05-27 19:16:05 +00:00
const server = ldap.createServer(serverOptions)
if (cluster.isMaster) {
2021-05-27 19:16:05 +00:00
for (let i = 0; i < os.cpus().length; i++) {
const thread = cluster.fork({
id: i
})
thread.id = i
thread.on('message', function () {
2021-05-27 19:16:05 +00:00
})
threads.push(thread)
}
2021-05-27 19:16:05 +00:00
server.listen(1389, function () {
console.log('ldapjs listening at ' + server.url)
})
} else {
2021-05-27 19:16:05 +00:00
const threadId = process.env.id
serverOptions.connectionRouter = () => {
console.log('should not be hit')
}
2021-05-27 19:16:05 +00:00
process.on('message', (msg, socket) => {
switch (msg.type) {
case 'connection':
server.newConnection(socket)
socket.resume()
console.log('ldapjs client connection accepted on ' + threadId.toString())
}
})
2021-05-27 19:16:05 +00:00
server.search('dc=example', function (req, res) {
console.log('ldapjs search initiated on ' + threadId.toString())
const obj = {
dn: req.dn.toString(),
attributes: {
objectclass: ['organization', 'top'],
o: 'example'
}
}
2021-05-27 19:16:05 +00:00
if (req.filter.matches(obj.attributes)) { res.send(obj) }
2021-05-27 19:16:05 +00:00
res.end()
})
}