helene
Version:
Real-time Web Apps for Node.js
83 lines • 2.98 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisTransport = exports.RedisKey = void 0;
const redis_1 = require("redis");
const utils_1 = require("../../utils");
exports.RedisKey = {
CLIENTS: 'helene:clients',
};
/**
* This is mainly used to propagate events to other instances when running node in a cluster.
*/
class RedisTransport {
opts;
pub;
sub;
server;
static defaultRedisOpts = {
url: 'redis://localhost:6379',
};
constructor(server, opts) {
this.server = server;
this.opts = Object.assign({}, RedisTransport.defaultRedisOpts, opts);
this.connect().catch(console.error);
}
async connect() {
this.pub = (0, redis_1.createClient)({
...RedisTransport.defaultRedisOpts,
...this.opts,
});
this.sub = this.pub.duplicate();
await this.pub.connect();
await this.sub.connect();
await this.sub.pSubscribe(utils_1.RedisListeners.EVENTS, redisMessage => {
const { event, channel, message } = utils_1.Presentation.decode(redisMessage);
// Do not add a debugger here, it will cause an infinite loop since it
// triggers an event this also goes through the transport.
this.server.channel(channel).propagate(event, message);
});
this.server.emit(utils_1.ServerEvents.REDIS_CONNECT);
}
async publish(event, channel = utils_1.NO_CHANNEL, message) {
if (!this.pub)
return;
// Do not add a debugger here, it will cause an infinite loop since it
// triggers an event this also goes through the transport.
return this.pub.publish(utils_1.RedisListeners.EVENTS, utils_1.Presentation.encode({
event,
channel,
message,
}));
}
async close() {
if (this.pub) {
await this.pub.del(`helene:clients:${this.server.uuid}`);
await this.pub.sRem(`helene:servers`, this.server.uuid);
}
if (this.pub?.isOpen)
await this.pub.quit();
if (this.sub?.isOpen)
await this.sub.quit();
this.pub = undefined;
this.sub = undefined;
}
async getStats() {
let clientCount = 0;
let userCount = 0;
const users = new Set();
const servers = await this.pub.sMembers(`helene:servers`);
for (const server of servers) {
clientCount += await this.pub.sCard(`helene:clients:${server}`);
userCount += await this.pub.sCard(`helene:users:${server}`);
const serverUsers = await this.pub.sMembers(`helene:users:${server}`);
serverUsers.forEach(user => users.add(user));
}
return {
clientCount,
userCount,
users: Array.from(users),
};
}
}
exports.RedisTransport = RedisTransport;
//# sourceMappingURL=redis-transport.js.map