actionhero
Version:
The reusable, scalable, and quick node.js API server for stateless and stateful applications
84 lines (83 loc) • 3.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.redis = void 0;
const uuid = require("uuid");
const index_1 = require("./../index");
var redis;
(function (redis) {
/**
* Publish a message to all other Actionhero nodes in the cluster. Will be authenticated against `api.config.serverToken`
* ```js
* let payload = {
* messageType: 'myMessageType',
* serverId: api.id,
* serverToken: api.config.general.serverToken,
* message: 'hello!'
* }
*
* await api.redis.publish(payload)
* ```
*/
async function publish(payload) {
const channel = index_1.config.general.channel;
const connection = index_1.api.redis.clients.client;
const stringPayload = JSON.stringify(payload);
if (connection.status !== "close" && connection.status !== "end") {
return connection.publish(channel, stringPayload);
}
else {
(0, index_1.log)(`cannot send message, redis disconnected`, "error", {
channel,
payload,
});
}
}
redis.publish = publish;
/**
* Invoke a command on all servers in this cluster.
*/
async function doCluster(method, args = [], connectionId, waitForResponse = false) {
const messageId = uuid.v4();
const payload = {
messageType: "do",
serverId: index_1.id,
serverToken: index_1.config.general.serverToken,
messageId: messageId,
method: method,
connectionId: connectionId,
args: args, // [1,2,3]
};
// we need to be sure that we build the response-handling promise before sending the request to Redis
// it is possible for another node to get and work the request before we resolve our write
// see https://github.com/actionhero/actionhero/issues/1244 for more information
if (waitForResponse) {
return new Promise(async (resolve, reject) => {
const timer = setTimeout(() => reject(new Error("RPC Timeout")), index_1.config.general.rpcTimeout);
index_1.api.redis.rpcCallbacks[messageId] = { timer, resolve, reject };
try {
await redis.publish(payload);
}
catch (e) {
clearTimeout(timer);
delete index_1.api.redis.rpcCallbacks[messageId];
throw e;
}
});
}
else {
return redis.publish(payload);
}
}
redis.doCluster = doCluster;
async function respondCluster(messageId, response) {
const payload = {
messageType: "doResponse",
serverId: index_1.id,
serverToken: index_1.config.general.serverToken,
messageId: messageId,
response: response, // args to pass back, including error
};
await redis.publish(payload);
}
redis.respondCluster = respondCluster;
})(redis || (exports.redis = redis = {}));