resend-delay.js
2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
var LRU = require('lru-cache');
var winston = require('winston');
var logger;
var topupRequest;
var resendHandlers = LRU({max: 2000, maxAge: 1000 * 3600 * 36});
function init(options) {
if (!options) {
console.log('Undefined options, terminating....');
process.exit(1);
}
if (options.config) {
config = options.config;
} else {
console.log('Undefined options.config, terminating....')
process.exit(1);
}
if (options.topupRequest) {
topupRequest = options.topupRequest;
} else {
console.log('Undefined options.topupRequest, terminating....')
process.exit(1);
}
if (options.logger) {
logger = options.logger;
} else {
logger = new winston.Logger({
transports: [
new (winston.transports.Console)()
]
});
}
}
function cancel(task) {
var requestId;
if (typeof task === 'string') {
requestId = task;
} else {
requestId = task.requestId;
}
if (!requestId) {
logger.warn('Undefined request id for resend delay, something wrong');
return;
}
var oldHandler = resendHandlers.get(requestId);
if (!oldHandler) {
logger.verbose('Undefined old handler for resend delay, skip', {request_id: requestId});
return;
}
logger.verbose('Canceling resend delay', {task: oldHandler.task});
try {
if (oldHandler.handler) {
clearTimeout(oldHandler.handler);
}
else {
logger.warn('Undefined oldhandler.handler on resend delay', {request_id: requestId});
}
}
catch(e) {
logger.warn('Resend delay got exception on clearTimeout', {request_id: requestId, err: e});
};
try {
resendHandlers.del(requestId);
}
catch(e) {
logger.warn('Resend relay got exception on resendHandlers.del', {request_id: requestId, err: e});
};
}
function register(task) {
if (!task.requestId) {
logger.warn('Invalid task on resendDelay')
return;
}
if (!config || !config.globals || !Number(config.globals.auto_resend_delay_secs) || !Number(config.globals.auto_resend_delay_max)) {
return;
}
var retry = Number(config.globals.auto_resend_delay_max);
var oldHandler = resendHandlers.get(task.requestId);
if (oldHandler) {
retry = oldHandler.retry - 1;
cancel(task);
}
if (retry <= 0) {
logger.verbose('Resend delay retry exceeded', {task: task});
cancel(task);
return;
}
logger.verbose('Registering resend delay task request', {task: task, delay: config.globals.auto_resend_delay_secs, retry: retry});
var handlerData = {
handler: setTimeout(topupRequest, Number(config.globals.auto_resend_delay_secs) * 1000, task),
task: task,
retry: retry
}
resendHandlers.set(task.requestId, handlerData);
}
exports.init = init;
exports.cancel = cancel;
exports.register = register;