Just moved code around for some minor optimization

This commit is contained in:
2015-06-11 21:38:48 +02:00
parent 16d3afcf9e
commit fbb171a913
2 changed files with 392 additions and 377 deletions
+126 -111
View File
@@ -60,13 +60,13 @@ function smsResp(status, callback) {
localSmsId = sms.smsId; localSmsId = sms.smsId;
} }
tasks.push(async.apply( tasks[i] = sms.session.sendReturn.bind(
sms.session.sendReturn, sms.session,
sms.pduObjs[i].pduObj, sms.pduObjs[i].pduObj,
status, status,
{'message_id': localSmsId}, {'message_id': localSmsId},
false false
)); );
i ++; i ++;
} }
@@ -155,94 +155,75 @@ function smsDlr(status, callback) {
sms.session.send(dlrPduObj, false, callback); sms.session.send(dlrPduObj, false, callback);
} }
/** function incOurSeqNr() {
* Generic session function this.ourSeqNr = this.ourSeqNr + 1;
*
* @param obj sock - socket object
* @return obj (returnObj)
*/
function session(sock) {
var returnObj = new events.EventEmitter();
log.silly('larvitsmpp: lib/session.js: session() - New session started from ' + sock.remoteAddress + ':' + sock.remotePort);
returnObj.loggedIn = false;
// Sequence number used for commands initiated from us
returnObj.ourSeqNr = 1;
// Make the socket transparent via the returned emitter
returnObj.sock = sock;
/**
* Increase our sequence number
*/
returnObj.incOurSeqNr = function() {
returnObj.ourSeqNr = returnObj.ourSeqNr + 1;
// If we pass the maximum, start over at 1 // If we pass the maximum, start over at 1
if (returnObj.ourSeqNr > 2147483646) { if (this.ourSeqNr > 2147483646) {
returnObj.ourSeqNr = 1; this.ourSeqNr = 1;
} }
}; }
/** /**
* Close the socket * Close the socket
* Always use this function to close the socket so we get it on log * Always use this function to close the socket so we get it on log
*/ */
returnObj.closeSocket = function() { function closeSocket() {
log.verbose('larvitsmpp: lib/session.js: session() - closeSocket() - Closing socket for ' + sock.remoteAddress + ':' + sock.remotePort); log.verbose('larvitsmpp: lib/session.js: closeSocket() - Closing socket for ' + this.sock.remoteAddress + ':' + this.sock.remotePort);
if (returnObj.enqLinkTimer) { if (this.enqLinkTimer) {
log.debug('larvitsmpp: lib/session.js: session() - closeSocket() - enqLinkTimer found, clearing.'); log.debug('larvitsmpp: lib/session.js: closeSocket() - enqLinkTimer found, clearing.');
clearTimeout(returnObj.enqLinkTimer); clearTimeout(this.enqLinkTimer);
} }
sock.destroy(); this.sock.destroy();
}; }
/** /**
* Write PDU to socket * Write PDU to socket
* *
* @param buf or obj pdu - can also take PDU object * @param buf or obj pdu - can also take PDU object
* @param bol closeAfterSend - if true will close the socket after sending * @param bol closeAfterSend - if true will close the socket after sending
*/ */
returnObj.sockWrite = function(pdu, closeAfterSend) { function sockWrite(pdu, closeAfterSend) {
var that = this;
if ( ! Buffer.isBuffer(pdu)) { if ( ! Buffer.isBuffer(pdu)) {
utils.objToPdu(pdu, function(err, buffer) { utils.objToPdu(pdu, function(err, buffer) {
if (err) { if (err) {
log.warn('larvitsmpp: lib/session.js: session() - sockWrite() - Could not convert PDU to buffer'); log.warn('larvitsmpp: lib/session.js: sockWrite() - Could not convert PDU to buffer');
returnObj.closeSocket(); that.closeSocket();
return; return;
} }
returnObj.sockWrite(buffer); that.sockWrite(buffer);
}); });
return; return;
} }
try { try {
log.verbose('larvitsmpp: lib/session.js: session() - sockWrite() - sending PDU. SeqNr: ' + pdu.readUInt32BE(12) + ' cmd: ' + defs.cmdsById[pdu.readUInt32BE(4)].command + ' cmdStatus: ' + defs.errorsById[parseInt(pdu.readUInt32BE(8))] + ' hex: ' + pdu.toString('hex')); log.verbose('larvitsmpp: lib/session.js: sockWrite() - sending PDU. SeqNr: ' + pdu.readUInt32BE(12) + ' cmd: ' + defs.cmdsById[pdu.readUInt32BE(4)].command + ' cmdStatus: ' + defs.errorsById[parseInt(pdu.readUInt32BE(8))] + ' hex: ' + pdu.toString('hex'));
} catch (e) { } catch (e) {
log.error('larvitsmpp: lib/session.js: session() - sockWrite() - PDU buffer is invalid. Buffer hex: "' + pdu.toString('hex') + '"'); log.error('larvitsmpp: lib/session.js: sockWrite() - PDU buffer is invalid. Buffer hex: "' + pdu.toString('hex') + '"');
return; return;
} }
sock.write(pdu); this.sock.write(pdu);
if (closeAfterSend) { if (closeAfterSend) {
returnObj.closeSocket(); this.closeSocket();
} }
}; }
/** /**
* Send a PDU to the remote * Send a PDU to the remote
* *
* @param buf or obj pdu * @param buf or obj pdu
* @param bol closeAfterSend - Will close after return is fetched. Defaults to false (OPTIONAL) * @param bol closeAfterSend - Will close after return is fetched. Defaults to false (OPTIONAL)
* @param func callback(err, retPdu) (OPTIONAL) * @param func callback(err, retPdu) (OPTIONAL)
*/ */
returnObj.send = function(pdu, closeAfterSend, callback) { function send(pdu, closeAfterSend, callback) {
var pduObj = pdu, var pduObj = pdu,
err = null; err = null,
that = this;
// Make sure the pdu is an object // Make sure the pdu is an object
if (Buffer.isBuffer(pdu)) { if (Buffer.isBuffer(pdu)) {
@@ -252,15 +233,15 @@ function session(sock) {
return; return;
} }
returnObj.send(pduObj, closeAfterSend, callback); that.send(pduObj, closeAfterSend, callback);
}); });
return; return;
} }
// Make sure the sequence number is set and is correct // Make sure the sequence number is set and is correct
pduObj.seqNr = returnObj.ourSeqNr; pduObj.seqNr = this.ourSeqNr;
log.debug('larvitsmpp: lib/session.js: session() - returnObj.send() - Sending PDU to remote. pduObj: ' + JSON.stringify(pduObj)); log.debug('larvitsmpp: lib/session.js: send() - Sending PDU to remote. pduObj: ' + JSON.stringify(pduObj));
// If closeAndSend is omitted, put callback in its place // If closeAndSend is omitted, put callback in its place
if (typeof closeAfterSend === 'function') { if (typeof closeAfterSend === 'function') {
@@ -281,16 +262,16 @@ function session(sock) {
} }
// When the return is fetched, call the callback // When the return is fetched, call the callback
returnObj.on('incomingPduObj' + pduObj.seqNr, function(incPduObj) { this.on('incomingPduObj' + pduObj.seqNr, function(incPduObj) {
log.debug('larvitsmpp: lib/session.js: session() - returnObj.send() - returnObj.on(incomingPduObj) - cmdName: ' + incPduObj.cmdName + ' seqNr: ' + incPduObj.seqNr + ' cmdStatus: ' + incPduObj.cmdStatus); log.debug('larvitsmpp: lib/session.js: send() - this.on(incomingPduObj) - cmdName: ' + incPduObj.cmdName + ' seqNr: ' + incPduObj.seqNr + ' cmdStatus: ' + incPduObj.cmdStatus);
// Make sure this is the actual response to the sent PDU // Make sure this is the actual response to the sent PDU
if (incPduObj.isResp() && incPduObj.seqNr === pduObj.seqNr) { if (incPduObj.isResp() && incPduObj.seqNr === pduObj.seqNr) {
callback(null, incPduObj); callback(null, incPduObj);
if (closeAfterSend) { if (closeAfterSend) {
returnObj.closeSocket(); that.closeSocket();
} }
} else { } else {
err = new Error('Event triggered but incoming PDU is not a response or seqNr does not match. isResp: ' + incPduObj.isResp().toString() + ' incSeqNr: ' + incPduObj.seqNr + ' expected seqNr: ' + pduObj.seqNr); err = new Error('Event triggered but incoming PDU is not a response or seqNr does not match. isResp: ' + incPduObj.isResp().toString() + ' incSeqNr: ' + incPduObj.seqNr + ' expected seqNr: ' + pduObj.seqNr);
@@ -300,13 +281,13 @@ function session(sock) {
}); });
// Increase our internal sequence number // Increase our internal sequence number
returnObj.incOurSeqNr(); this.incOurSeqNr();
// Write the PDU to socket // Write the PDU to socket
returnObj.sockWrite(pduObj); this.sockWrite(pduObj);
}; }
/** /**
* Send a return to given PDU * Send a return to given PDU
* *
* @param obj or buf pdu * @param obj or buf pdu
@@ -315,7 +296,9 @@ function session(sock) {
* @param bol closeAfterSend - if true will close the socket after sending (OPTIONAL) * @param bol closeAfterSend - if true will close the socket after sending (OPTIONAL)
* @param func callback(err, retPdu) (OPTIONAL) * @param func callback(err, retPdu) (OPTIONAL)
*/ */
returnObj.sendReturn = function(pdu, status, params, closeAfterSend, callback) { function sendReturn(pdu, status, params, closeAfterSend, callback) {
var that = this;
if (typeof params === 'function') { if (typeof params === 'function') {
callback = params; callback = params;
params = undefined; params = undefined;
@@ -329,8 +312,8 @@ function session(sock) {
utils.pduReturn(pdu, status, params, function(err, retPdu) { utils.pduReturn(pdu, status, params, function(err, retPdu) {
if (err) { if (err) {
log.error('larvitsmpp: lib/session.js: session() - returnObj.sendReturn() - Could not create return PDU: ' + err.message); log.error('larvitsmpp: lib/session.js: sendReturn() - Could not create return PDU: ' + err.message);
returnObj.closeSocket(); that.closeSocket();
if (typeof callback === 'function') { if (typeof callback === 'function') {
callback(err); callback(err);
@@ -339,17 +322,17 @@ function session(sock) {
return; return;
} }
log.silly('larvitsmpp: lib/session.js: session() - returnObj.sendReturn() - Sending return PDU: ' + retPdu.toString('hex')); log.silly('larvitsmpp: lib/session.js: sendReturn() - Sending return PDU: ' + retPdu.toString('hex'));
returnObj.sockWrite(retPdu, closeAfterSend); that.sockWrite(retPdu, closeAfterSend);
if (typeof callback === 'function') { if (typeof callback === 'function') {
callback(null, retPdu); callback(null, retPdu);
} }
}); });
}; }
/** /**
* Send an SMS * Send an SMS
* *
* @param obj smsOptions * @param obj smsOptions
@@ -359,7 +342,7 @@ function session(sock) {
* dlr - boolean defaults to false * dlr - boolean defaults to false
* @param func callback(err, smsIds, retPduObjs) * @param func callback(err, smsIds, retPduObjs)
*/ */
returnObj.sendSms = function(smsOptions, callback) { function sendSms(smsOptions, callback) {
var pduObj = {}; var pduObj = {};
pduObj.cmdName = 'submit_sm'; pduObj.cmdName = 'submit_sm';
@@ -377,29 +360,21 @@ function session(sock) {
// Check if we must split this message into multiple // Check if we must split this message into multiple
if (utils.bitCount(smsOptions.message) > 1120) { if (utils.bitCount(smsOptions.message) > 1120) {
returnObj.sendLongSms(smsOptions, callback); this.sendLongSms(smsOptions, callback);
return; return;
} }
log.debug('larvitsmpp: lib/session.js: returnObj.sendSms() - pduObj: ' + JSON.stringify(pduObj)); log.debug('larvitsmpp: lib/session.js: sendSms() - pduObj: ' + JSON.stringify(pduObj));
returnObj.send(pduObj, function(err, retPduObj) { this.send(pduObj, function(err, retPduObj) {
if (typeof callback === 'function') { if (typeof callback === 'function') {
callback(err, [retPduObj.params.message_id], [retPduObj]); callback(err, [retPduObj.params.message_id], [retPduObj]);
} }
}); });
}; }
// Temporary storage for long sms parts /**
// These should be cleared if they lingre to long to avoid memory leaks
returnObj.longSmses = {};
// Temporary storage for DLRs to long smses
// We keep them like this to be able to simulate a single DLR when all parts have gotten DLRs
returnObj.longSmsDlrs = {};
/**
* Send a longer SMS than 1120 bits * Send a longer SMS than 1120 bits
* *
* @param obj smsOptions * @param obj smsOptions
@@ -409,8 +384,9 @@ function session(sock) {
* dlr - boolean defaults to false * dlr - boolean defaults to false
* @param func callback(err, smsId, retPduObj) * @param func callback(err, smsId, retPduObj)
*/ */
returnObj.sendLongSms = function(smsOptions, callback) { function sendLongSms(smsOptions, callback) {
var smsIds = [], var that = this,
smsIds = [],
retPduObjs = [], retPduObjs = [],
msgs = utils.splitMsg(smsOptions.message), msgs = utils.splitMsg(smsOptions.message),
encoding = defs.encodings.detect(smsOptions.message); // Set encoding once for all message parts encoding = defs.encodings.detect(smsOptions.message); // Set encoding once for all message parts
@@ -434,16 +410,16 @@ function session(sock) {
pduObj.params.registered_delivery = 0x01; pduObj.params.registered_delivery = 0x01;
} }
log.debug('larvitsmpp: lib/session.js: returnObj.sendLongSms() - pduObj: ' + JSON.stringify(pduObj)); log.debug('larvitsmpp: lib/session.js: sendLongSms() - pduObj: ' + JSON.stringify(pduObj));
returnObj.send(pduObj, function(err, retPduObj) { that.send(pduObj, function(err, retPduObj) {
smsIds.push(retPduObj.params.message_id); smsIds.push(retPduObj.params.message_id);
retPduObjs.push(retPduObj); retPduObjs.push(retPduObj);
log.silly('larvitsmpp: lib/session.js: returnObj.sendLongSms() - Callback from returnObj.send() gotten'); log.silly('larvitsmpp: lib/session.js: sendLongSms() - Got callback from that.send()');
if (typeof callback === 'function' && smsIds.length === msgs.length) { if (typeof callback === 'function' && smsIds.length === msgs.length) {
log.silly('larvitsmpp: lib/session.js: returnObj.sendLongSms() - All callbacks returned, run the parent callback.'); log.silly('larvitsmpp: lib/session.js: sendLongSms() - All callbacks returned, run the parent callback.');
callback(err, smsIds, retPduObjs); callback(err, smsIds, retPduObjs);
} }
}); });
@@ -454,16 +430,16 @@ function session(sock) {
} }
sendPart(0); sendPart(0);
}; }
// Store long smses in the temporary storage // Store long smses in the temporary storage
returnObj.longSms = function(pduObj) { function longSms(pduObj) {
var smsGroupId = pduObj.params.short_message[3], var smsGroupId = pduObj.params.short_message[3],
smsParts = pduObj.params.short_message[4], smsParts = pduObj.params.short_message[4],
longSmsId = pduObj.params.source_addr + '_' + pduObj.params.destination_addr + '_' + smsGroupId; longSmsId = pduObj.params.source_addr + '_' + pduObj.params.destination_addr + '_' + smsGroupId;
if (returnObj.longSmses[longSmsId] === undefined) { if (this.longSmses[longSmsId] === undefined) {
returnObj.longSmses[longSmsId] = { this.longSmses[longSmsId] = {
'created': new Date(), 'created': new Date(),
'partsCount': parseInt(smsParts), 'partsCount': parseInt(smsParts),
'pduObjs': [{ 'pduObjs': [{
@@ -472,26 +448,27 @@ function session(sock) {
}] }]
}; };
} else { } else {
returnObj.longSmses[longSmsId].pduObjs.push({ this.longSmses[longSmsId].pduObjs.push({
'partNr': pduObj.params.short_message[5], // We save this here to easier sort the array later on 'partNr': pduObj.params.short_message[5], // We save this here to easier sort the array later on
'pduObj': pduObj 'pduObj': pduObj
}); });
} }
// Check the long messages tmp storage to see if we should handle them // Check the long messages tmp storage to see if we should handle them
returnObj.checkLongSmses(); this.checkLongSmses();
}; }
// Walk through the long sms storage to investigate if we can send complete messages along // Walk through the long sms storage to investigate if we can send complete messages along
// or should remove old ones // or should remove old ones
returnObj.checkLongSmses = function() { function checkLongSmses() {
var smsGroupId, var that = this,
smsGroupId,
smsGroup, smsGroup,
smsObj, smsObj,
i, i,
curPduObj; curPduObj;
log.silly('larvitsmpp: lib/session.js: session() - returnObj.checkLongSmses() - Running'); log.silly('larvitsmpp: lib/session.js: checkLongSmses() - Running');
// Sort function to sort group parts // Sort function to sort group parts
function sortLongSmsPdus(a, b) { function sortLongSmsPdus(a, b) {
@@ -508,22 +485,22 @@ function session(sock) {
// Call when complete SMS is received // Call when complete SMS is received
function smsReceived() { function smsReceived() {
returnObj.emit('sms', smsObj); that.emit('sms', smsObj);
// This needs to be ran if DLRs are sent for these messages // This needs to be ran if DLRs are sent for these messages
delete returnObj.longSmses[smsGroupId]; delete that.longSmses[smsGroupId];
} }
for (smsGroupId in returnObj.longSmses) { for (smsGroupId in this.longSmses) {
smsGroup = returnObj.longSmses[smsGroupId]; smsGroup = this.longSmses[smsGroupId];
// All parts are accounted for! Emit sms event and clear from tmp storage // All parts are accounted for! Emit sms event and clear from tmp storage
if (smsGroup.partsCount === smsGroup.pduObjs.length) { if (smsGroup.partsCount === smsGroup.pduObjs.length) {
log.debug('larvitsmpp: lib/session.js: session() - returnObj.checkLongSmses() - All parts accounted for in smsGroupId "' + smsGroupId + '", emitting sms event.'); log.debug('larvitsmpp: lib/session.js: checkLongSmses() - All parts accounted for in smsGroupId "' + smsGroupId + '", emitting sms event.');
smsObj = { smsObj = {
// These are needed for references here and there in functions // These are needed for references here and there in functions
'session': returnObj, 'session': that,
'pduObjs': smsGroup.pduObjs, 'pduObjs': smsGroup.pduObjs,
'from': smsGroup.pduObjs[0].pduObj.params.source_addr, 'from': smsGroup.pduObjs[0].pduObj.params.source_addr,
'to': smsGroup.pduObjs[0].pduObj.params.destination_addr, 'to': smsGroup.pduObjs[0].pduObj.params.destination_addr,
@@ -542,7 +519,7 @@ function session(sock) {
i = 0; i = 0;
while (smsObj.pduObjs[i] !== undefined) { while (smsObj.pduObjs[i] !== undefined) {
curPduObj = smsObj.pduObjs[i].pduObj; curPduObj = smsObj.pduObjs[i].pduObj;
curPduObj.session = returnObj; curPduObj.session = this;
smsObj.message += utils.decodeMsg(curPduObj.params.short_message, curPduObj.params.data_coding, curPduObj.params.short_message[0] + 1); smsObj.message += utils.decodeMsg(curPduObj.params.short_message, curPduObj.params.data_coding, curPduObj.params.short_message[0] + 1);
@@ -550,12 +527,50 @@ function session(sock) {
} }
smsReceived(); smsReceived();
} else if (moment(new Date()).diff(smsGroup.created, 'hours') > 24) { } else if (moment(new Date()).diff(smsGroup.created, 'hours') > 24) {
log.info('larvitsmpp: lib/session.js: session() - returnObj.checkLongSmses() - smsGroupId "' + smsGroupId + '" is removed from returnObj.longSmses due to being older than 24 hours.'); log.info('larvitsmpp: lib/session.js: checkLongSmses() - smsGroupId "' + smsGroupId + '" is removed from this.longSmses due to being older than 24 hours.');
delete returnObj.longSmses[smsGroupId]; delete this.longSmses[smsGroupId];
} }
} }
}; }
/**
* Generic session function
*
* @param obj sock - socket object
* @return obj (returnObj)
*/
function session(sock) {
var returnObj = new events.EventEmitter();
log.silly('larvitsmpp: lib/session.js: session() - New session started from ' + sock.remoteAddress + ':' + sock.remotePort);
returnObj.loggedIn = false;
// Sequence number used for commands initiated from us
returnObj.ourSeqNr = 1;
// Make the socket transparent via the returned emitter
returnObj.sock = sock;
returnObj.incOurSeqNr = incOurSeqNr;
returnObj.closeSocket = closeSocket;
returnObj.sockWrite = sockWrite;
returnObj.send = send;
returnObj.sendReturn = sendReturn;
returnObj.sendSms = sendSms;
// Temporary storage for long sms parts
// These should be cleared if they lingre to long to avoid memory leaks
returnObj.longSmses = {};
// Temporary storage for DLRs to long smses
// We keep them like this to be able to simulate a single DLR when all parts have gotten DLRs
returnObj.longSmsDlrs = {};
returnObj.sendLongSms = sendLongSms;
returnObj.longSms = longSms;
returnObj.checkLongSmses = checkLongSmses;
// Handle incomming commands. // Handle incomming commands.
// This is intended to be extended // This is intended to be extended
+1 -1
View File
@@ -29,7 +29,7 @@
"url": "https://github.com/larvit/larvitsmpp", "url": "https://github.com/larvit/larvitsmpp",
"type": "git" "type": "git"
}, },
"version": "0.0.3", "version": "0.0.4",
"readmeFilename": "README.md", "readmeFilename": "README.md",
"readme": "larvitsmpp", "readme": "larvitsmpp",
"bugs": { "bugs": {