@nestjs/microservices
Version:
Microservices for NestJS: message and event handlers over Kafka, RabbitMQ, NATS, Redis, MQTT, gRPC or TCP.
401 lines (400 loc) • 17.1 kB
JavaScript
import { REDIS_DEFAULT_HOST, REDIS_DEFAULT_PORT } from '../constants.js';
import { ClientProxy } from './client-proxy.js';
import { Logger } from '@nestjs/common';
import { isNumber, isString, loadPackage } from '@nestjs/common/internal';
/**
* @publicApi
*/
export class ClientRedis extends ClientProxy {
options;
logger = new Logger(ClientProxy.name);
subscriptionsCount = new Map();
// The reply channels whose subscription Redis has not acknowledged yet
pendingSubscriptions = new Set();
pubClient;
subClient;
connectionPromise = null;
isManuallyClosed = false;
wasInitialConnectionSuccessful = false;
closeCount = 0;
pendingEventListeners = [];
constructor(options) {
super();
this.options = options;
this.initializeSerializer(options);
this.initializeDeserializer(options);
}
getRequestPattern(pattern) {
return pattern;
}
getReplyPattern(pattern) {
return `${pattern}.reply`;
}
async close() {
this.closeCount++;
this.isManuallyClosed = true;
this.handleClose();
this.pubClient && (await this.quitClient(this.pubClient));
this.subClient && (await this.quitClient(this.subClient));
this.pubClient = this.subClient = null;
this.connectionPromise = null;
this.isManuallyClosed = false;
this.wasInitialConnectionSuccessful = false;
this.pendingEventListeners = [];
}
// `quit()` rejects when the command cannot be sent (e.g., while
// reconnecting with the offline queue disabled), which would leave the
// other client open and `close()` half done. Close the connection right
// away instead.
async quitClient(client) {
try {
await client.quit();
}
catch {
client.disconnect();
}
}
connect() {
if (this.connectionPromise) {
return this.connectionPromise;
}
const connectionPromise = this.handleConnection().catch(err => {
// Once the clients are connecting, the "reconnecting", "ready" and "end"
// listeners take over `connectionPromise`: ioredis keeps retrying in
// the background, and "end" resets the state once it gives up. If none
// of them did, nothing else is going to reset it, so do it here to let
// the next `connect()` call try again.
if (this.connectionPromise === connectionPromise) {
this.discardClients();
}
throw err;
});
this.connectionPromise = connectionPromise;
return connectionPromise;
}
/**
* Drops the current pub/sub pair, so the next `connect()` call starts over
* with new clients. Events the dropped clients emit from now on are ignored.
*/
discardClients() {
const clients = [this.pubClient, this.subClient];
this.pubClient = this.subClient = null;
this.connectionPromise = null;
this.wasInitialConnectionSuccessful = false;
for (const client of clients) {
// An ended client has no connection or pending retry left to stop
if (client && client.status !== 'end') {
client.disconnect();
}
}
}
/**
* Whether `client` belongs to the current pub/sub pair, as opposed to a
* client that has been dropped and is still shutting down.
*/
isCurrentClient(client) {
return client === this.pubClient || client === this.subClient;
}
async handleConnection() {
// `close()` may run while the clients are being created. It has no client
// to quit then, so the ones created afterwards must not be connected (or
// replace the clients of a newer `connect()` call).
const closeCount = this.closeCount;
const pubClient = await this.createClient();
if (this.closeCount !== closeCount) {
throw new Error('Connection closed');
}
this.pubClient = pubClient;
const subClient = await this.createClient();
if (this.closeCount !== closeCount) {
throw new Error('Connection closed');
}
this.subClient = subClient;
[this.pubClient, this.subClient].forEach((client, index) => {
const type = index === 0 ? 'pub' : 'sub';
this.registerErrorListener(client);
this.registerReconnectListener(client);
this.registerReadyListener(client);
this.registerEndListener(client);
this.pendingEventListeners.forEach(({ event, callback }) => client.on(event, (...args) => callback(type, ...args)));
});
await Promise.all([this.subClient.connect(), this.pubClient.connect()]);
}
async createClient() {
const clientInfoTag = this.getOptionsProp(this.options, 'clientInfoTag');
const redisPackage = await loadPackage('ioredis', ClientRedis.name, () => import('ioredis'));
const RedisClient = redisPackage.default || redisPackage;
return new RedisClient({
host: REDIS_DEFAULT_HOST,
port: REDIS_DEFAULT_PORT,
...this.getClientOptions(),
...(clientInfoTag && { clientInfoTag }),
lazyConnect: true,
});
}
registerErrorListener(client) {
client.addListener("error" /* RedisEventsMap.ERROR */, (err) => this.logger.error(err));
}
registerReconnectListener(client) {
client.on("reconnecting" /* RedisEventsMap.RECONNECTING */, () => {
if (this.isManuallyClosed || !this.isCurrentClient(client)) {
return;
}
this.connectionPromise = Promise.reject('Error: Connection lost. Trying to reconnect...');
// Prevent unhandled rejections
this.connectionPromise.catch(() => { });
this._status$.next("reconnecting" /* RedisStatus.RECONNECTING */);
if (this.wasInitialConnectionSuccessful) {
this.logger.log('Reconnecting to Redis...');
}
});
}
registerReadyListener(client) {
client.on("ready" /* RedisEventsMap.READY */, () => {
if (!this.isCurrentClient(client) ||
this.pubClient?.status !== 'ready' ||
this.subClient?.status !== 'ready') {
return;
}
this.connectionPromise = Promise.resolve();
this._status$.next("connected" /* RedisStatus.CONNECTED */);
this.logger.log('Connected to Redis. Subscribing to channels...');
if (!this.wasInitialConnectionSuccessful) {
this.wasInitialConnectionSuccessful = true;
const handleResponse = this.createResponseCallback();
this.subClient.on(this.options.returnBuffers ? 'messageBuffer' : 'message',
// ioredis does not handle the promise, so a rejection would crash
// the process
(channel, buffer) => handleResponse(channel, buffer).catch(err => this.logger.error(err)));
}
});
}
registerEndListener(client) {
client.on('end', () => {
if (this.isManuallyClosed || !this.isCurrentClient(client)) {
return;
}
this._status$.next("disconnected" /* RedisStatus.DISCONNECTED */);
this.handleClose();
this.logger.error('Disconnected from Redis.');
// ioredis gave up on this client (retry attempts not specified or
// exhausted), so drop the pair and let the next `connect()` call
// create a new one
this.discardClients();
});
}
handleClose() {
if (this.routingMap.size > 0) {
const err = new Error('Connection closed');
const callbacks = [...this.routingMap.values()];
this.routingMap.clear();
for (const callback of callbacks) {
try {
callback({ err });
}
catch (callbackErr) {
// A failing callback must not keep the remaining requests pending
// nor prevent the connection from being closed.
this.logger.error(callbackErr);
}
}
}
this.subscriptionsCount.clear();
this.pendingSubscriptions.clear();
}
getClientOptions() {
const retryStrategy = (times) => this.createRetryStrategy(times);
return {
...(this.options || {}),
retryStrategy,
};
}
on(event, callback) {
// Kept until `close()`, so the pairs created later get it as well
this.pendingEventListeners.push({ event, callback });
if (this.subClient && this.pubClient) {
this.subClient.on(event, (...args) => callback('sub', ...args));
this.pubClient.on(event, (...args) => callback('pub', ...args));
}
}
unwrap() {
if (!this.pubClient || !this.subClient) {
throw new Error('Not initialized. Please call the "connect" method first.');
}
return [this.pubClient, this.subClient];
}
createRetryStrategy(times) {
if (this.isManuallyClosed) {
return undefined;
}
if (!this.getOptionsProp(this.options, 'retryAttempts')) {
this.logger.error('Redis connection closed and retry attempts not specified');
return;
}
if (times > this.getOptionsProp(this.options, 'retryAttempts', 0)) {
this.logger.error('Retry time exhausted');
return;
}
return this.getOptionsProp(this.options, 'retryDelay', 5000);
}
createResponseCallback() {
return async (channel, buffer) => {
let packet;
try {
packet = JSON.parse(buffer);
}
catch (err) {
this.logger.debug('Redis response packet is not in json format, bypassing...');
packet = buffer;
}
let incomingResponse;
try {
incomingResponse = await this.deserializer.deserialize(packet);
}
catch (error) {
// Only the deserializer knows the id, so no request can be failed here.
// Nobody awaits this listener, so a rejection would crash the process.
this.logger.error(`Dropped a response that the deserializer failed on: ${error}`, error?.stack);
return;
}
const { err, response, isDisposed, id } = incomingResponse;
const callback = this.routingMap.get(id);
if (!callback) {
if (Buffer.isBuffer(buffer))
this.logger.debug('You have to parse your buffer on your own to get id from it, because it is not in json format');
// Whoever can publish on the reply channel chooses the id. Request
// ids are strings, and an object can throw when converted to one
// (`{"toString":1}`), so only a string or a number is printed.
const printableId = isString(id) || isNumber(id) ? id : `(${typeof id})`;
this.logger.debug(`No matching callback found for Redis response packet with id: ${printableId}`);
return;
}
if (isDisposed || err) {
return callback({
err,
response,
isDisposed: true,
});
}
callback({
err,
response,
});
};
}
publish(partialPacket, callback) {
let undoBookkeeping = () => { };
try {
const packet = this.assignPacketId(partialPacket);
const pattern = this.normalizePattern(partialPacket.pattern);
const serializedPacket = this.serializer.serialize(packet);
const responseChannel = this.getReplyPattern(pattern);
// Counted right away rather than once published, as in ClientMqtt: a
// request that waits for Redis to acknowledge the subscription depends
// on it as well. Torn down meanwhile, it gives the subscription up, and
// a concurrent request that finishes first does not unsubscribe.
const subscriptionsCount = this.subscriptionsCount.get(responseChannel) || 0;
this.subscriptionsCount.set(responseChannel, subscriptionsCount + 1);
let isCounted = true;
undoBookkeeping = () => {
if (!isCounted) {
return;
}
isCounted = false;
this.setSubscriptionsCount(responseChannel, (this.subscriptionsCount.get(responseChannel) || 1) - 1);
this.routingMap.delete(packet.id);
};
const publishPacket = () => {
if (!isCounted) {
return;
}
try {
this.pubClient.publish(this.getRequestPattern(pattern), JSON.stringify(serializedPacket), err => {
if (err && isCounted) {
undoBookkeeping();
callback({ err });
}
});
}
catch (err) {
// The broker can acknowledge the subscription later, so this runs
// outside the outer catch and has to undo its own work. Only the
// bookkeeping though, as in #17822: the next request on this
// pattern subscribes again.
undoBookkeeping();
callback({ err });
}
};
const cleanup = () => {
if (!isCounted) {
return;
}
isCounted = false;
// Sent on the connection that subscribes, so after the SUBSCRIBE of
// a request that is torn down before its acknowledgement
this.unsubscribeFromChannel(responseChannel);
this.routingMap.delete(packet.id);
};
// Registered before the subscription is acknowledged, so that
// `handleClose()` fails a request that still waits for it as well
this.routingMap.set(packet.id, callback);
// Requests are published on another connection than the one that
// subscribes, so a request that finds the channel still waiting for its
// acknowledgement subscribes as well rather than publishing right away,
// which the reply could overtake.
if (subscriptionsCount <= 0 ||
this.pendingSubscriptions.has(responseChannel)) {
this.pendingSubscriptions.add(responseChannel);
this.subClient.subscribe(responseChannel, (err) => {
if (!isCounted) {
// Torn down meanwhile (e.g., failed by `handleClose()`), which
// gave the subscription up
return;
}
if (err) {
undoBookkeeping();
return callback({ err });
}
this.pendingSubscriptions.delete(responseChannel);
publishPacket();
});
}
else {
publishPacket();
}
return cleanup;
}
catch (err) {
undoBookkeeping();
callback({ err });
return () => { };
}
}
dispatchEvent(packet) {
const pattern = this.normalizePattern(packet.pattern);
const serializedPacket = this.serializer.serialize(packet);
return new Promise((resolve, reject) => this.pubClient.publish(pattern, JSON.stringify(serializedPacket), err => err ? reject(err) : resolve()));
}
unsubscribeFromChannel(channel) {
const subscriptionCount = this.subscriptionsCount.get(channel);
this.setSubscriptionsCount(channel, subscriptionCount - 1);
if (subscriptionCount - 1 <= 0) {
// ioredis rejects when the connection is gone (e.g. in "handleClose")
this.subClient.unsubscribe(channel, () => { });
}
}
/**
* Keeps only the channels that requests wait on. Patterns can be built from
* request data (e.g., one per device), so a channel nobody waits on any
* longer must not leave an entry behind.
*/
setSubscriptionsCount(channel, count) {
if (count > 0) {
this.subscriptionsCount.set(channel, count);
}
else {
this.subscriptionsCount.delete(channel);
this.pendingSubscriptions.delete(channel);
}
}
}