NodeJS Queue performing delayed HTTP Request are weird - node.js

Dear helpful people in the internet,
i started to write an HTTP Queue. I have a Request Class, which works if I use it without context, but with my queue active, my http requests wont work. I can't figure out why.
var t = new Request('s','s', function(){});
t.perform();
When i perform the request like this in any file. It works. But when i use it with my queue (index.js,L19 to L22) no request is performed. The function Request.perform() were executed, but the HTTP-Request isn't there.
Sorry for my english, I'm not native ^^
index.js
const http = require('http');
const https = require('https');
const {Request} = require('./classes/Request');
const queue = require('./queue.js');
queue.setCallbackFunction(performRequest);
function performRequest(request){
console.log("2");
request.perform();
}
var req = new Request('','', function(response,body){
console.log(JSON.stringify(response) + " :: " + body);
});
queue.add(req);
queue.js
var queue = [];
var ratelimits = [];
module.exports.add = function(request){
queue.push(request);
run_queue();
}
module.exports.setCallbackFunction = function(cb){
call = cb;
}
module.exports.setRateLimits = function(ratelimitings){
ratelimits = [];
for(var z in ratelimitings){
var x = ratelimitings[z];
var data = {};
data.max = x[0];
data.time = x[1];
data.count = 0;
ratelimits[x[1]] = data;
}
}
function run_queue(){
var q;
if(queue.length > 0){
q = run_request(queue[0]);
while (q == true) {
queue.shift();
if(queue.length > 0)
q = run_request(queue[0]);
}
}
}
function run_request(request){
for(var z in ratelimits){
var x = ratelimits[z];
if(x.max <= x.count){
return false;
}
}
for(var z in ratelimits){
var x = ratelimits[z];
if(x.count === 0){
setTimeout(function(z){
console.log(JSON.stringify(x));
ratelimits[z].count = 0;
run_queue();
},z,z);
}
x.count++;
//console.log(JSON.stringify(x));
}
//DO REQUEST
console.log("1")
call(request);
return true;
}
Request.js
exports.Request = class{
constructor(host,path,cb){
this.path = path;
this.cb = cb;
this.host = host
}
perform(){
console.log("3");
var https = require('https');
var options = {
host: 'www.example.com',
path: '/'
};
var callback = function(response) {
//HERE THIS GETS NEVER CALLED BECAUSE OF WHATEVER WHILE ITS IN THE QUEUE
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
https.request(options, callback).end();
}
}
All 3 console.logs get printed, but the Request Callback Never gets called.

The problem is caused by function run_queue:
function run_queue(){
var q;
if(queue.length > 0){
q = run_request(queue[0]);
while (q == true) {
queue.shift();
if(queue.length > 0)
q = run_request(queue[0]);
}
}
}
After run_request() is executed successfully (HTTP request is sent), queue.shift() is called immediately, which means the req object you just added into the queue is removed from queue array and qualified for Garbage Collection. As one HTTP request/response will normally cost a few milliseconds, it is very likely that before response is retrieved, the req object is GCed (destroyed). Thus, no callback will be invoked, as the HTTP connection does not exist any more.
To change queue but keep req object from GC, you need to save it somewhere else, such as a temporary array (the infinite loop bug is also fix in following code):
var tmp = [];
function run_queue(){
var q;
if(queue.length > 0){
q = run_request(queue[0]);
while (q == true) {
tmp.push(queue.shift());
if(queue.length > 0) {
q = run_request(queue[0]);
} else {
q = false;
}
}
}
}
Please note the above code is only for demo. In production code, you need to manage the tmp array -- when one request is done, it needs to be removed from tmp. Otherwise, tmp array will keep growing...

Related

Titanium http request leak

I have to make a load of subsequent http requests to load product images into the app as it has to function in an offline mode.
Around 2000 calls.
The http client seems toi have a memory leak which causes the persistent mbytes in "instruments" to rise to around 200 without being garbaged.
After use of the http client it is being set to null.
I have tried setting the file property of the httpclient without any success
I have set the unload function to only call the callback function which in turn calls the http send function again (thus looping through the 2000 products to get the respective pictures)
I changed from SDK 7.5.0.v20180824022007 to SDK 8.1.0.v20190423134840 and even SDK 9.0.0.v20181031080737 but the problem remains
the code of my http common module:
function HttpClient(options = {}) {
this.root = options.root || "ROOT_OF_API";
this.endpoint = options.endpoint || false;
this.needsChecksum = options.needsChecksum || false;
this.data = {};
this.method = options.method || "Post";
this.timeout = options.timeout || 5000;
this.calculateChecksum = function () {
var moment = require('alloy/moment');
if (!Alloy.Models.user.authenticated()) {
return false;
}
var sp = (moment().unix() - Alloy.Models.meta.get("timeDiff"))
var hash = Ti.Utils.md5HexDigest("nX" + sp + "FossilSFAapp" + Alloy.Models.user.get('token').substring(10, 14) + "CS")
var checksum = sp + "-" + hash.substring(4, 8)
this.data.checksum = checksum
}
};
HttpClient.prototype.setData = function (data) {
this.data = data
};
HttpClient.prototype.send = function (callback) {
// set new checksum for request if is needed
if (this.needsChecksum) {
this.calculateChecksum()
}
// add app version
if (this.method === "POST") {
this.data.appversion = Ti.App.version;
}
// send
var client = Ti.Network.createHTTPClient({
onload: function () {
callback({
success: true
})
},
onerror: function(e) {
callback({
message: e.messgae,
success: false
})
},
timeout: this.timeout
});
client.open(this.method, this.root + this.endpoint);
if (this.setFile) {
client.file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, this.fileName);
}
client.setRequestHeader('Content-Type', 'application/json');
client.send(JSON.stringify(this.data));
client = null;
};
module.exports = HttpClient;
and then the module is used in the product model like so:
var HttpClient = require('./HttpClient');
var httpClient = new HttpClient();
function getImage (i) {
if (collection.at(i) && collection.at(i).get('iimage0') && collection.at(i).needsImageUpdate()) {
httpClient.endpoint = collection.at(i).get('acarticlenumber') +".jpg";
httpClient.fileName = 'productImages/' + collection.at(i).get('acarticlenumber') + '.jpg'
httpClient.send(function(e){
if (i < collection.length) {
i++
getImage(i)
} else {
finished()
}
});
} else {
if (i < collection.length) {
i++
getImage(i)
} else {
finished()
}
}
}
// start getting images at index 0
getImage(0)
anyone have an idea why these memory leaks appear ?
It only ever occurs when actually sending the http request.

node wait for iteration to complete before callback

I have a lambda function in node.js to send a push notification.
In that function I need to iterate through my users sending a notification for each one prior to the callback.
Ideally I would like the iteration to perform in parallel.
What would be the best way to do this?
My code is currently as follows but it does not work as expected because the last user is not always the last to be handled:
var apnProvider = new apn.Provider(options);
var iterationComplete = false;
for (var j = 0; j < users.length; j++) {
if (j === (users.length - 1)) {
iterationComplete = true;
}
var deviceToken = users[j].user_device_token;
var deviceBadge = users[j].user_badge_count;
var notification = new apn.Notification();
notification.alert = message;
notification.contentAvailable = 1;
notification.topic = "com.example.Example";
apnProvider.send(notification, [deviceToken]).then((response) => {
if (iterationComplete) {
context.succeed(event);
}
});
}
Use Promise.all instead - map each user's associated apnProvider.send call to a Promise in an array, and when all Promises in the array are resolved, call the callback:
const apnProvider = new apn.Provider(options);
const userPromises = users.map((user) => {
const deviceToken = user.user_device_token;
const deviceBadge = user.user_badge_count;
const notification = new apn.Notification();
notification.alert = message;
notification.contentAvailable = 1;
notification.topic = "com.example.Example";
return apnProvider.send(notification, [deviceToken]);
})
Promise.all(userPromises)
.then(() => {
context.succeed(event);
})
.catch(() => {
// handle errors
});

making node wait for db call to get completed

I just started writing node.js code.
I'm writing a code that extracts data from a pdf file, cleans it up and stores it in a database (using couchdb and accessing that using nano library).
The problem is that the calls are being made asynchronously... so the database get calls (i make some get calls to get a few affiliation files during the clean up) get completed only after the program runs resulting in variables being undefined. is there any way around this?
I've reproduced my code below
const fs = require('fs');
const os = require('os');
var couchDB = require('couch-db').CouchDB;
var pdf_table_extractor = require('pdf-table-extractor');
const filename = "PQ-PRI-0005-1806-01-0000_quoteSlipForLIBVIDGI1.pdf"
var nano = require('nano')('https://couchadmin:difficulttoguessmypassword#dbdev.perilwise.com');
var server = new couchDB('https://db.url.com');
server.auth("admin","admin");
var db = nano.db.use('pwfb');
var temp = [];
//New callView function
async function callView(){
try{
const doc = await view('liabilitymdm','pi');
for (var i =0; i<doc.rows.length;i++){
tmp.push(doc.rows[i]);
};
return doc;
} catch(e){
console.log(e);
};
};
function suc(result){
let ttmp = [];
console.log(result);
var pageTables = result.pageTables;
var firstPageTables = pageTables[0].tables;
ttmp = callView();
//this console log shows Promise { <pending> }
console.log(ttmp)
for (var k = 0; k < firstPageTables.length; k++) {
var temp = firstPageTables[k];
if (temp.length > 0) {
dump.push(temp);
}
}
// console.log(dump);
var insurer = filename.substr(37,8);
read_quote_slip(insurer,dump);
}
var read_quote_slip = (insurer,data) => {
console.log("read_quote_slip correctly entered");
var finOut = {};
if (insurer === "LIBVIDGI"){
finOut.insurer = insurer;
finOut.policyType = data[2][0].replace(/Quotation for/g,"");
finOut.natureOfWork = data[13][3];
let dedpos = indexGetter(data, "Deductible")[0];
finOut.deductible = data[dedpos+1][0];
let cov = indexGetter(data, "Coverage Territory and Jurisdiction")[0];
finOut.coverageTerritory = data[cov+1][0].replace(/Territory/g,"");
finOut.coverageJurisdiction = data[cov+2][0].replace(/Jurisdiction/g,"");
let ext = indexGetter(data,"Extensions")[0];
finOut.coverage = data[ext+1][0].split(/\r?\n/);
let majexc = indexGetter(data,"Major Exclusions")[0];
finOut.exclusions = data[majexc+1][0].split(/\r?\n/);
let prdtl = indexGetter(data,"Description")[0];
let prm = premiumcompute(data,prdtl,dedpos);
finOut.premium = prm;
finCleaned = libvidgi_cleaned(finOut);
// console.log(finCleaned);
}
}
var indexGetter = (words,toFind) => {
var finindex = [];
for (var i = 0; i < words.length; i++){
for (var j = 0; j < words[i].length; j++){
if(words[i][j].indexOf(toFind) >=0 ){
finindex.push(i);
}
}
}
return finindex;
}
var premiumcompute = (data, from, to) => {
let finprem = [];
let numbop = to - from - 2;
let incr = 0;
for (var i = from+2; i < to; i++){
let pr = {};
pr.option = incr+1;
pr.sumInsured = data[i][2].replace(/ /g,"");
pr.premium = data[i][data[i].length - 1].replace(/ /g,"");
finprem.push(pr);
incr +=1;
}
return finprem;
}
var libvidgi_cleaned = (finOut) => {
return finOut;
}
var fal = (result) => {
console.log(result);
console.log("there was an error");
}
var readPDFFile = function(filename){
//Decide which insurer from the filename
// console.log(filename);
console.log(filename.substr(37,8)+"Printed on line 38");
insurer = filename.substr(37,8)
pdf_table_extractor(filename, (result) => {suc(result)} , fal);
}
var libvidgi_data_extract = (data) => {
console.log(data);
let arr = data.pageTables.tables;
for (var i = 0; i <= arr.length; i++ ){
console.log(arr[i]);
}
}
readPDFFile(filename);
This answer assumes you are using Node.js > v7.6
Since db.view accepts a callback, and you wish to wait for it to finish, one solution will be to promisify it - meaning to turn it into a promise which can be awaited. You can use a library like Bluebird or you can even use Node's builtin promisify util. Then you can rewrite callViews:
const {promisify} = require('util');
const view = promisify(db.view);
async function callView() {
try {
const doc = await view('liabilitymdm', 'pi');
// the async operation is now guaranteed to be done
// (if there is an error it will be caught by the catch clause)
for (var i = 0; i < doc.rows.length; i++) {
temp.push(doc.rows[i]);
}
console.log(temp);
} catch (e) {
}
}
If you are not using Node.js > v7.6 (and cannot use async\await you can still utilize promises, by using their then method:
const {promisify} = require('util');
const view = promisify(db.view);
function callView() {
view('liabilitymdm', 'pi')
.then(doc => {
for (var i = 0; i < doc.rows.length; i++) {
temp.push(doc.rows[i]);
}
console.log(temp);
return temp;
})
.then(temp => {
console.log(temp);
})
.catch(e => {});
}
Notice how the first then is returning something which is used in a later then.
To make Node run asynchronously, you can use the keywords async and await.
They work like this:
async function doSomething () {
const formattedData = formatData();
const result = await db.postToDatabase(formattedData);
// the below will not happen until the above line is finished
doSomethingElse(result);
}
It's pretty simple in Node to get functions to execute asynchronously. Just put the async keyword at the beginning of the function definition and then put await in front of anything that you want to block execution until completed.

Can't set headers after they are sent in get request

router.get('/getpostcode', function(req, res){
console.log(req.query.suburb);
var options = {
url: 'http://apiurl?suburb=' + req.query.suburb + "&state=" + req.query.state ,
headers: {
'auth-key': key
}
}
request(options, callback);
function callback(error, response, body){
if(!error && response.statusCode == 200){
info = JSON.parse(body);
info = info.localities.locality;
if( Object.prototype.toString.call( info ) == '[object Array]' ){
for ( var x = 0 ; x < info.length ; x++ ){
var locx = info[x].location;
var qsuburb = req.query.suburb;
if( locx == qsuburb.toUpperCase() ){
res.send( { 'postcode': info[x].postcode } );
}
}
} else if (Object.prototype.toString.call( info ) != '[object Array]') {
var locx = info.location;
var qsuburb = req.query.suburb;
if ( locx == qsuburb.toUpperCase() ){
res.send( { 'postcode': info.postcode } );
}
}
}
}
});
So, I am trying to request data from an API and then based on that data, I am then sending some data back. My code is as above.
Unfortunately, in the callback function, when I am running a loop to find a specific element that I will then send back to the client, when sending that element to client, I am getting the error as shown in the title.
This does not occur when there is no loop and I simply send one element of the data back.
Any ideas on what this could be?
You are sending response more than one for one request, write res.send or JSON outside the loop.
for (var x = 0; x < info.length; x++) {
var locx = info[x].location;
var qsuburb = req.query.suburb;
var postcodes = [];
if (locx == qsuburb.toUpperCase()) {
postcodes.push({
'postcode': info[x].postcode
});
}
res.json(postcodes);
}
You are reaching the res.send function call at least twice in your flow and this is not allowed. That function must be called once to send the response to the client.
Yeah, As #Rahul said, It is not allowed to send response more than one time for the same request - You must be getting same post code, so you either need to store your postcode in a variable and send it after loop overs or you can use a break. Though it is not advisable to use a break in complex loops in the pretty simple loop you can leverage its usage.
for (var x = 0; x < info.length; x++) {
var locx = info[x].location;
var qsuburb = req.query.suburb;
if (locx == qsuburb.toUpperCase()) {
res.send({
'postcode': info[x].postcode
});
break;
}
}
Or as following:
for (var x = 0; x < info.length; x++) {
var locx = info[x].location;
var qsuburb = req.query.suburb;
vat postcode = = null;
if (locx == qsuburb.toUpperCase()) {
postcode = info[x].postcode
}
}
res.send({
postcode
});

Resolving a deferred Q multiple times

As I know deferred can be resolved only once and also nodejs caches the required module at the first step in order to prevent loading it every single time, but what I want to do is renewing deferred Q object each time I want to resolve/reject a returned value.
This is my server code :
// server.js
app.get('/api/posts', function(req,res,next){
var insta = require('./upRunner'); // this's the main obstacle
insta.returner().then(function(data){
// ....
};
});
and the code for ./upRunner.js is :
// upRunner.js
...
var defer = Q.defer();
upRunner();
function extractor(body) {
var $ = cheerio.load(body), scripts= [];
$('script').each(function(i, elem){
scripts[i] = $(this).text();
});
var str = scripts[6],
newData = JSON.parse(str.substring(str.indexOf("{"), str.lastIndexOf(";"))).entry_data.TagPage[0].tag.media.page_info;
grabber(str);
return newData;
}
function grabber(str) {
newData = JSON.parse(str.substring(str.indexOf("{"), str.lastIndexOf(";"))).entry_data.TagPage[0].tag.top_posts.nodes;
newData.sort(dynamicSort('-date'));
newData.forEach(function(elem,index,array){
if (instaImages.length >= 10) {
defer.resolve(instaImages);
} else {
instaImages.push(elem);
}
});
}
function upRunner(newData){
profilePage = !(tagPage = URL.includes("/tags/") ? true : false);
if (!newData) {
request(URL,{jar:true}, function(err, resp, body){
var $ = cheerio.load(body), scripts= [];
$('script').each(function(i, elem){
scripts[i] = $(this).text();
});
var str = scripts[6],
newData = JSON.parse(str.substring(str.indexOf("{"), str.lastIndexOf(";"))).entry_data.TagPage[0].tag.media.page_info;
upRunner(newData);
});
} else {
if (newData.has_next_page) {
requester(URL, newData.end_cursor).then(function(body){
newData = extractor(body);
upRunner(newData);
});
} else {
console.log('it\'s finished\n');
}
function returner() {
return deferred.promise;
}
exports.returner = returner;
As you see I'm almost renewing upRunner returner deferred promise each time server get /api/posts address, but the problem is the deferred object still return the old resolved value.
There is the grabber function which resolve value, so defer can not be localized in a single function.
Try to initialized deferred value locally to get new resolve value.
function returner() {
var defer= $q.defer();
return deferred.promise;
};
exports.returner = returner;

Resources