pull.js
14.4 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
/* eslint-disable no-param-reassign */
const MODULE_NAME = 'KOMODO-SDK.PULL';
const DEFAULT_REQUEST_TIMEOUT_MS = 20 * 1000;
const IS_DEBUG = process.env.KOMODO_SDK_DEBUG_PULL;
const request = require('request');
const stringify = require('json-stringify-pretty-compact');
const logger = require('tektrans-logger');
const urljoin = require('url-join');
const uniqid = require('uniqid');
const config = require('../config');
const matrix = require('../matrix');
if (config.control_panel && (config.control_panel.listen_port || config.control_panel.port)) {
// eslint-disable-next-line global-require
require('../control-panel');
}
const heartbeat = require('../heartbeat');
const coreUrl = require('../core-url');
const taskArchive = require('./task-archive');
const MAX_SLEEP_BEFORE_RESEND_MS = 500;
const DELAY_AFTER_NO_TASK_MS = 500;
let isOnDelayAfterNoTask = false;
let pullTaskLocked = false;
if (config.handler_name) {
process.title = `KOMODO-GW@${config.handler_name}`;
}
matrix.sdk_pending_tasks_count = 0;
matrix.sdk_unresponsed_tasks_count = 0;
matrix.sdk_pending_with_response_tasks_count = 0;
if (!matrix.sdk_pending_tasks) {
matrix.sdk_pending_tasks = [];
}
if (!matrix.sdk_unresponsed_tasks) {
matrix.sdk_unresponsed_tasks = [];
}
if (!matrix.sdk_pending_with_response_tasks) {
matrix.sdk_pending_with_response_tasks = [];
}
heartbeat.setModuleType('gateway');
let partner;
function onNoTask() {
isOnDelayAfterNoTask = true;
setTimeout(() => {
isOnDelayAfterNoTask = false;
}, DELAY_AFTER_NO_TASK_MS);
}
function setPartner(_partner) {
partner = _partner;
}
function isPaused() {
return matrix.paused;
}
function getRemoteProduct(product) {
const remoteProduct = config.remote_products[product];
return remoteProduct || product;
}
function incrementCounterTrx() {
matrix.counter.trx += 1;
}
function updateTaskOnMatrix(trxId, rc) {
trxId = Number(trxId);
const unresponsedTaskIdx = matrix.sdk_unresponsed_tasks.indexOf(trxId);
if (unresponsedTaskIdx >= 0) {
matrix.sdk_unresponsed_tasks.splice(unresponsedTaskIdx, 1);
}
matrix.sdk_unresponsed_tasks_count = matrix.sdk_unresponsed_tasks.length;
if (rc === '68' || rc === 68) {
const pendingWithResponseTaskIdx = matrix.sdk_pending_with_response_tasks.indexOf(trxId);
if (pendingWithResponseTaskIdx < 0) {
matrix.sdk_pending_with_response_tasks.push(trxId);
// eslint-disable-next-line max-len
matrix.sdk_pending_with_response_tasks_count = matrix.sdk_pending_with_response_tasks.length;
}
} else {
const pendingTaskIdx = matrix.sdk_pending_tasks.indexOf(trxId);
if (pendingTaskIdx >= 0) {
matrix.sdk_pending_tasks.splice(pendingTaskIdx, 1);
matrix.sdk_pending_tasks_count = matrix.sdk_pending_tasks.length;
}
const pendingWithResponseTaskIdx = matrix.sdk_pending_with_response_tasks.indexOf(trxId);
if (pendingWithResponseTaskIdx >= 0) {
matrix.sdk_pending_with_response_tasks.splice(pendingWithResponseTaskIdx, 1);
// eslint-disable-next-line max-len
matrix.sdk_pending_with_response_tasks_count = matrix.sdk_pending_with_response_tasks.length;
}
}
}
function putTaskToMatrix(task) {
const trxId = Number(task.trx_id);
if (matrix.sdk_unresponsed_tasks.indexOf(trxId) < 0) {
matrix.sdk_unresponsed_tasks.push(trxId);
matrix.sdk_unresponsed_tasks_count = matrix.sdk_unresponsed_tasks.length;
}
if (matrix.sdk_pending_tasks.indexOf(trxId) < 0) {
matrix.sdk_pending_tasks.push(trxId);
matrix.sdk_pending_tasks_count = matrix.sdk_pending_tasks.length;
}
}
function replaceRc(originalRc) {
if (!config || !config.replace_rc) {
return originalRc;
}
return config.replace_rc[originalRc] || originalRc;
}
function report(data, xidFromCaller) {
const xid = xidFromCaller || uniqid();
let corePullReportUrl;
if (data && data.trx_id && data.rc) {
updateTaskOnMatrix(data.trx_id, data.rc);
}
if (coreUrl) {
corePullReportUrl = urljoin(coreUrl, '/pull/report');
} else if (config && config.pull_url && config.pull_url.report) {
corePullReportUrl = config.pull_url.report.replace('<CORE_APIKEY>', config.core_apikey);
}
if (!corePullReportUrl) {
logger.warn(`${MODULE_NAME} C23CC601: Unknown CORE report url`);
return;
}
if (
config && config.push_server && config.push_server.apikey
&& config.push_server.advice && config.push_server.advice.url
&& config.push_server.advice.port
) {
if (!data.misc) {
data.misc = {};
}
data.misc.advice_url = config.push_server.advice.url;
}
const sdkTrxIdAdder = Number(config.sdk_trx_id_adder) || 0;
let trxId = Number(data.trx_id) - sdkTrxIdAdder;
if (sdkTrxIdAdder) {
logger.verbose(`${MODULE_NAME} 3E0016E8: REPORT: Adjusting trx id`, {
xid,
sdkTrxIdAdder,
trxId: data.trx_id,
adjustedTrxId: trxId,
});
}
if (trxId <= 0) {
logger.warn(`${MODULE_NAME} 6A8C7303: REPORT: calculated trx_id is a negative number, using uncalculated trx_id`, {
xid,
uncalculated: data.trx_id,
calculated: trxId,
sdkTrxIdAdder,
});
trxId = data.trx_id;
}
const options = {
url: corePullReportUrl,
form: {
trx_id: trxId,
rc: replaceRc(data.rc),
rc_from_handler: data.rc_from_handler,
message: typeof data.message === 'string' ? data.message : stringify(data.message),
handler: config.handler_name,
sn: data.sn,
amount: data.amount,
balance: data.balance,
raw: data.raw,
misc: data.misc,
product: data.product
|| (data.misc && data.misc.task && typeof data.misc.task.product === 'string' && data.misc.task.product)
|| null,
remote_product: data.remote_product
|| (data.misc && data.misc.task && typeof data.misc.task.remote_product === 'string' && data.misc.task.remote_product)
|| null,
detail: data.detail || null,
},
};
if (!config.do_not_verbose_log_report) {
logger.verbose(`${MODULE_NAME} 2110168C: Report to CORE using HTTP POST`, { xid });
}
request.post(options, (error, response) => {
if (error) {
logger.warn(`${MODULE_NAME} B1CA595F: Error reporting to CORE`, { xid, error });
// eslint-disable-next-line no-use-before-define
resendReport(data);
} else if (response.statusCode !== 200) {
logger.warn(`${MODULE_NAME} 4B73BD23: Error reporting to CORE, http response status is not 200`, {
xid, requestOptions: options, http_response_status: response.statusCode,
});
// eslint-disable-next-line no-use-before-define
resendReport(data);
} else if (!config.do_not_verbose_log_report) {
logger.verbose(`${MODULE_NAME} 379A25AA: Report has been sent to CORE`, { xid, requestOptions: options });
}
});
}
function resendReport(data) {
const sleepBeforeResend = Math.round(Math.random() * MAX_SLEEP_BEFORE_RESEND_MS);
logger.verbose(`${MODULE_NAME} DEE44715: Resend report to CORE in ${sleepBeforeResend} ms`);
setTimeout(
() => {
report(data);
},
sleepBeforeResend,
);
}
function forwardCoreTaskToPartner(coreMessage, startTime, xid) {
let task;
try {
task = JSON.parse(coreMessage);
} catch (e) {
logger.warn(`${MODULE_NAME} E757F11A: Exception on parsing CORE pull task response`, {
xid, coreMessage, eCode: e.code, eMessage: e.message,
});
return;
}
if (config.sdk_pull_only_postpaid) {
logger.warn(`${MODULE_NAME} E6662C4F: Got task on sdk_pull_only_postpaid. It should not be happens`, { xid, task });
report({
trx_id: task.trx_id,
rc: '40',
message: {
xid,
msg: 'GATEWAY ini diset hanya untuk transaksi postpaid (config.sdk_pull_only_postpaid)',
},
});
return;
}
const corePullRequestTime = startTime ? (new Date() - startTime) / 1000 : null;
incrementCounterTrx();
task.remote_product = getRemoteProduct(task.product);
const sdkTrxIdAdder = Number(config.sdk_trx_id_adder);
if (sdkTrxIdAdder) {
const newTrxId = Number(task.trx_id) + sdkTrxIdAdder;
logger.verbose(`${MODULE_NAME} 873BA19B: Adjusting trx id`, {
xid,
sdkTrxIdAdder,
originalTrxId: task.trx_id,
newTrxId,
});
task.trx_id = newTrxId;
}
putTaskToMatrix(task);
const createdTs = new Date(task.created);
const queueTime = ((new Date()) - createdTs) / 1000;
logger.info(`${MODULE_NAME} 7F131334: Got task from CORE`, {
xid,
trx_id: task.trx_id,
destination: task.destination,
product: task.product,
queue_time: queueTime,
core_pull_request_time: corePullRequestTime,
});
taskArchive.get(task, (res) => {
if (res && partner.advice) {
partner.advice(task, xid);
} else {
partner.buy(task, xid);
}
});
}
function pullTask() {
if (isPaused()) {
if (IS_DEBUG) {
logger.verbose(`${MODULE_NAME} 76370FE5: PULL TASK paused`);
}
return;
}
if (isOnDelayAfterNoTask && !config.disable_delay_after_no_task) {
return;
}
if (!partner) {
if (IS_DEBUG) {
logger.verbose(`${MODULE_NAME} FFB54A2A: PULL TASK disabled because of undefined partner`);
}
return;
}
if (matrix && matrix.not_ready) {
if (IS_DEBUG) {
logger.verbose(`${MODULE_NAME} 68BDA23B: PULL TASK paused because of gateway is not ready`);
}
return;
}
let corePullTaskUrl;
if (coreUrl) {
corePullTaskUrl = urljoin(coreUrl, '/pull/task');
} else if (config && config.pull_url && config.pull_url.task) {
corePullTaskUrl = config.pull_url.task.replace('<CORE_APIKEY>', config.core_apikey);
}
if (!corePullTaskUrl) {
logger.warn(`${MODULE_NAME} 5F0681B7: Unknown CORE task url`);
return;
}
if (pullTaskLocked) {
if (IS_DEBUG) {
logger.verbose(`${MODULE_NAME} B81F0CCD: PULL TASK paused because LOCKED`);
}
return;
}
pullTaskLocked = true;
const xid = uniqid();
const bodyOrQs = {
handler: config.handler_name,
products: (config.products || []).join(','),
locations: config.locations && config.locations.length ? config.locations.join(',') : 'ALL',
advice_url: (
config && config.push_server
&& config.push_server.apikey && config.push_server.advice
&& config.push_server.advice.url && config.push_server.advice.port
&& config.push_server.advice.url
) || null,
api_url: (
config && config.apiserver
&& config.apiserver.apikey && config.apiserver.url && config.apiserver.url
) || null,
cp_url: (
config && config.control_panel && config.control_panel.url && config.control_panel.url
) || null,
komodosdk_type: matrix.komodosdk_type,
komodosdk_version: matrix.komodosdk_version,
};
const options = {
url: corePullTaskUrl,
timeout: config.request_timeout || DEFAULT_REQUEST_TIMEOUT_MS,
};
if (config.pull_task_use_post) {
if (IS_DEBUG) {
logger.verbose(`${MODULE_NAME} CB855B30: PULL TASK using HTTP POST`, { xid });
}
options.method = 'POST';
options.form = bodyOrQs;
} else {
if (IS_DEBUG) {
logger.verbose(`${MODULE_NAME} BA2EF935: PULL TASK using HTTP GET`, { xid });
}
options.method = 'GET';
options.qs = bodyOrQs;
}
if (config && config.debug_request_task_to_core) {
logger.verbose(`${MODULE_NAME} 0642E25C: Requesting task to CORE`, {
xid, url: options.url, method: options.method, body_or_qs: bodyOrQs,
});
}
const startTime = new Date();
request(options, (error, response, body) => {
pullTaskLocked = false;
const lameLimit = 10 * 1000;
const deltaTime = new Date() - startTime;
if (deltaTime > lameLimit) {
logger.warn(`${MODULE_NAME} B892DC43: LAME-PULL: PULL response from CORE exceeds ${lameLimit} secs`, { xid, deltaTime });
}
if (error) {
if (matrix.core_is_healthy) {
logger.warn(`${MODULE_NAME} FB762F4A: Error pulling task from CORE`, { xid, error });
}
matrix.core_is_healthy = false;
onNoTask();
return;
}
if (response.statusCode !== 200) {
if (matrix.core_is_healthy) {
logger.warn(`${MODULE_NAME} 8943EECB: CORE http response status code for pull task is not 200`, {
xid,
http_response_status: response.statusCode,
});
}
matrix.core_is_healthy = false;
onNoTask();
return;
}
if (!matrix.core_is_healthy) {
logger.verbose(`${MODULE_NAME} 099F5B3C: CORE is healthy`, { xid });
}
matrix.core_is_healthy = true;
if (body === 'NONE') {
onNoTask();
return;
}
if (body === 'LOCKED') {
return;
}
forwardCoreTaskToPartner(body, startTime, xid);
});
}
function pause() {
matrix.paused = true;
}
function resume() {
matrix.paused = false;
}
function initMatrix() {
matrix.counter = {
trx: 0,
};
}
initMatrix();
if (!global.KOMODO_SDK_DISABLE_PULL) {
setInterval(pullTask, config.pull_interval_ms || 1000);
logger.verbose(`${MODULE_NAME} B6AEB920: Pull task every ${config.pull_interval_ms || 1000} ms`);
} else {
logger.info(`${MODULE_NAME} DEC80C55: Pull task disabled because of global.KOMODO_SDK_DISABLE_PULL flag`);
}
exports.setPartner = setPartner;
exports.isPaused = isPaused;
exports.pause = pause;
exports.resume = resume;
exports.report = report;
exports.getRemoteProduct = getRemoteProduct;