Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: queue job execution timeout #620

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 23 additions & 18 deletions app/cronjob/alive.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,36 @@ const moment = require('moment-timezone');
const config = require('config');
const aliveHelper = require('./alive/helper');
const { slack } = require('../helpers');
const queue = require('./trailingTradeHelper/queue');

const execute = async logger => {
logger.info('Alive: Notify balance');

try {
// 1. Get account info
const accountInfo = await aliveHelper.getAccountInfo(logger);
const aliveFn = async () => {
try {
// 1. Get account info
const accountInfo = await aliveHelper.getAccountInfo(logger);

let message = '*Account Balance:*\n```';
let message = '*Account Balance:*\n```';

accountInfo.balances.forEach(b => {
message += `- ${b.asset}: Free ${(+b.free).toFixed(
3
)}, Locked ${(+b.locked).toFixed(3)}\n`;
});
message += '```\n';
message += `_Last Updated: ${moment(accountInfo.updateTime, 'x')
.tz(config.get('tz'))
.format('YYYY-MM-DD HH:mm:ss')} (${config.get('tz')})_`;
accountInfo.balances.forEach(b => {
message += `- ${b.asset}: Free ${(+b.free).toFixed(
3
)}, Locked ${(+b.locked).toFixed(3)}\n`;
});
message += '```\n';
message += `_Last Updated: ${moment(accountInfo.updateTime, 'x')
.tz(config.get('tz'))
.format('YYYY-MM-DD HH:mm:ss')} (${config.get('tz')})_`;

slack.sendMessage(message);
} catch (e) {
logger.error(e, 'Execution failed.');
slack.sendMessage(`Execution failed\n\`\`\`${e.message}\`\`\``);
}
slack.sendMessage(message);
} catch (e) {
logger.error(e, 'Execution failed.');
slack.sendMessage(`Execution failed\n\`\`\`${e.message}\`\`\``);
}
};

queue.execute(logger, '_CRONJOB_ALIVE', { processFn: aliveFn });
};

module.exports = { execute };
20 changes: 14 additions & 6 deletions app/cronjob/trailingTradeHelper/queue.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,20 @@ const executeJob = async (funcLogger, symbol, jobPayload) => {

// Execute the job
if (jobPayload.processFn) {
// processFn
await jobPayload.processFn(
funcLogger,
symbol,
_.get(jobPayload, 'correlationId')
);
// processFn with 20 seconds timeout
await Promise.race([
jobPayload.processFn(
funcLogger,
symbol,
_.get(jobPayload, 'correlationId')
),
new Promise(r =>
// eslint-disable-next-line no-promise-executor-return
setTimeout(r, 20000).then(
logger.error({ symbol }, `Queue ${symbol} job timeout`)
)
)
]);
}

// Postprocess after executeTrailingTrade
Expand Down
32 changes: 1 addition & 31 deletions app/server-cronjob.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,6 @@ const { maskConfig } = require('./cronjob/trailingTradeHelper/util');

const { executeAlive, executeTrailingTradeIndicator } = require('./cronjob');

const fulfillWithTimeLimit = async (logger, timeLimit, task, failureValue) => {
let timeout;
const timeoutPromise = new Promise(resolve => {
timeout = setTimeout(() => {
logger.error(
{ tag: 'job-timeout' },
`Failed to run the job within ${timeLimit}ms.`
);

resolve(failureValue);
}, timeLimit);
});

const response = await Promise.race([task, timeoutPromise]);

/* istanbul ignore next */
if (timeout) {
// the code works without this but let's be safe and clean up the timeout.
clearTimeout(timeout);
}
return response;
};

const runCronjob = async serverLogger => {
const logger = serverLogger.child({ server: 'cronjob' });
logger.info(
Expand Down Expand Up @@ -59,14 +36,7 @@ const runCronjob = async serverLogger => {

const moduleLogger = logger.child({ job: jobName, uuid: uuidv4() });

// Make sure the job running within 20 seconds.
// If longer than 20 seconds, something went wrong.
await fulfillWithTimeLimit(
moduleLogger,
20000,
executeJob(moduleLogger),
null
);
executeJob(moduleLogger);

jobInstances[jobName].taskRunning = false;
},
Expand Down