tovarish-relayer/lib/start.js

99 lines
3.1 KiB
JavaScript
Raw Normal View History

2024-11-13 04:42:13 +03:00
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const process_1 = __importDefault(require("process"));
const cluster_1 = __importDefault(require("cluster"));
const config_1 = require("./config");
const services_1 = require("./services");
if (cluster_1.default.isWorker) {
new services_1.Router(JSON.parse(process_1.default.env.relayerConfig), Number(process_1.default.env.forkId));
}
else {
start();
}
async function forkRouter({ relayerConfig, logger, syncManager, relayerWorker, forkId, }) {
const worker = cluster_1.default.fork({
relayerConfig: JSON.stringify(relayerConfig),
forkId,
});
worker
.on('exit', (code) => {
logger.error(`Router Worker ${forkId} died with code ${code}, respawning...`);
setTimeout(() => {
forkRouter({
relayerConfig,
logger,
syncManager,
relayerWorker,
forkId,
});
}, 5000);
})
.on('message', async (msg) => {
const { msgId, type } = msg;
if (type === 'status') {
worker.send({
msgId,
syncManagerStatus: syncManager.getStatus(),
pendingWorks: relayerWorker.pendingWorks(),
});
return;
}
if (type === 'job') {
const work = relayerWorker.getWork({
id: msg.id,
});
worker.send({
msgId,
...work,
});
return;
}
if (type === 'tornadoWithdraw') {
const newWork = await relayerWorker.createWork({
netId: msg.netId,
contract: msg.contract,
proof: msg.proof,
args: msg.args,
});
worker.send({
msgId,
...newWork,
});
return;
}
if (type === 'errors') {
worker.send({
msgId,
errors: [...syncManager.errors, ...relayerWorker.errors],
});
return;
}
});
}
async function start() {
const relayerConfig = (0, config_1.getRelayerConfig)();
const logger = (0, services_1.getLogger)('[Main]', relayerConfig.logLevel);
console.log('Relayer config', relayerConfig);
await (0, services_1.checkProviders)(relayerConfig, logger);
const syncManager = new services_1.SyncManager(relayerConfig);
await syncManager.syncEvents();
const relayerWorker = new services_1.RelayerWorker(relayerConfig, syncManager);
setInterval(() => syncManager.syncEvents(), relayerConfig.syncInterval * 1000);
// Spawn website
let i = 0;
while (i < relayerConfig.workers) {
forkRouter({
relayerConfig,
logger,
syncManager,
relayerWorker,
forkId: i,
});
i++;
}
logger.info(`Spawned ${i} Router Workers`);
}