UNPKG

openhim-core

Version:

The OpenHIM core application that provides logging and routing of http requests

228 lines (209 loc) 7.11 kB
var Q, SDC, application, config, copyMapWithEscapedReservedCharacters, domain, logger, os, sdc, setFinalStatus, statsdServer, transactionStatus, transactions; transactions = require("../model/transactions"); logger = require("winston"); Q = require("q"); config = require('../config/config'); statsdServer = config.get('statsd'); application = config.get('application'); SDC = require('statsd-client'); os = require('os'); domain = (os.hostname()) + "." + application.name + ".appMetrics"; sdc = new SDC(statsdServer); exports.transactionStatus = transactionStatus = { PROCESSING: 'Processing', SUCCESSFUL: 'Successful', COMPLETED: 'Completed', COMPLETED_W_ERR: 'Completed with error(s)', FAILED: 'Failed' }; copyMapWithEscapedReservedCharacters = function(map) { var escapedMap, k, v; escapedMap = {}; for (k in map) { v = map[k]; if (k.indexOf('.') > -1 || k.indexOf('$') > -1) { k = k.replace('.', '\uff0e').replace('$', '\uff04'); } escapedMap[k] = v; } return escapedMap; }; exports.storeTransaction = function(ctx, done) { var headers, ref, ref1, tx; logger.info('Storing request metadata for inbound transaction'); ctx.requestTimestamp = new Date(); headers = copyMapWithEscapedReservedCharacters(ctx.header); tx = new transactions.Transaction({ status: transactionStatus.PROCESSING, clientID: ctx.authenticated._id, channelID: ctx.authorisedChannel._id, clientIP: ctx.authenticated.ip, request: { host: (ref = ctx.host) != null ? ref.split(':')[0] : void 0, port: (ref1 = ctx.host) != null ? ref1.split(':')[1] : void 0, path: ctx.path, headers: headers, querystring: ctx.querystring, body: ctx.body, method: ctx.method, timestamp: ctx.requestTimestamp } }); if (ctx.parentID && ctx.taskID) { tx.parentID = ctx.parentID; tx.taskID = ctx.taskID; } if (ctx.authorisedChannel.requestBody === false || tx.request.body === '') { tx.request.body = ''; if (ctx.method === 'POST' || ctx.method === 'PUT' || ctx.method === 'PATCH') { tx.canRerun = false; } } return tx.save(function(err, tx) { if (err) { logger.error('Could not save transaction metadata: ' + err); return done(err); } else { ctx.transactionId = tx._id; ctx.header['X-OpenHIM-TransactionID'] = tx._id.toString(); return done(null, tx); } }); }; exports.storeResponse = function(ctx, done) { var headers, ref, res, update; headers = copyMapWithEscapedReservedCharacters(ctx.response.header); res = { status: ctx.response.status, headers: headers, body: !ctx.response.body ? "" : ctx.response.body.toString(), timestamp: ctx.response.timestamp }; if (ctx.authorisedChannel.responseBody === false) { res.body = ''; } update = { response: res }; if (((ref = ctx.mediatorResponse) != null ? ref.status : void 0) != null) { update.status = ctx.mediatorResponse.status; } if (ctx.mediatorResponse) { if (ctx.mediatorResponse.orchestrations) { update.orchestrations = ctx.mediatorResponse.orchestrations; } if (ctx.mediatorResponse.properties) { update.properties = ctx.mediatorResponse.properties; } } return transactions.Transaction.findOneAndUpdate({ _id: ctx.transactionId }, update, { runValidators: true }, function(err, tx) { logger.info("stored primary response for " + tx._id); if (err) { logger.error('Could not save response metadata for transaction: ' + ctx.transactionId + '. ' + err); return done(err); } if (tx === void 0 || tx === null) { logger.error('Could not find transaction: ' + ctx.transactionId); return done(err); } return done(); }); }; exports.storeNonPrimaryResponse = function(ctx, routeObject, done) { if (ctx.authorisedChannel.responseBody === false) { routeObject.response.body = ''; } if (ctx.transactionId != null) { return transactions.Transaction.findByIdAndUpdate(ctx.transactionId, { $push: { "routes": routeObject } }, function(err, tx) { if (err) { logger.error(err); } return done(tx); }); } else { return logger.error("the request has no transactionId"); } }; exports.setFinalStatus = setFinalStatus = function(ctx, callback) { var ref, ref1, transactionId; transactionId = ''; if ((ref = ctx.request) != null ? (ref1 = ref.header) != null ? ref1["X-OpenHIM-TransactionID"] : void 0 : void 0) { transactionId = ctx.request.header["X-OpenHIM-TransactionID"]; } else { transactionId = ctx.transactionId.toString(); } return transactions.Transaction.findById(transactionId, function(err, tx) { var i, len, ref2, ref3, ref4, ref5, ref6, ref7, ref8, route, routeFailures, routeSuccess; if (((ref2 = ctx.mediatorResponse) != null ? ref2.status : void 0) != null) { logger.info("The transaction status has been set to " + ctx.mediatorResponse.status + " by the mediator"); return callback(tx); } else { routeFailures = false; routeSuccess = true; if (ctx.routes) { ref3 = ctx.routes; for (i = 0, len = ref3.length; i < len; i++) { route = ref3[i]; if ((500 <= (ref4 = route.response.status) && ref4 <= 599)) { routeFailures = true; } if (!((200 <= (ref5 = route.response.status) && ref5 <= 299))) { routeSuccess = false; tx.status = transactionStatus.COMPLETED; } } } if ((500 <= (ref6 = ctx.response.status) && ref6 <= 599)) { tx.status = transactionStatus.FAILED; } else { if (routeFailures) { tx.status = transactionStatus.COMPLETED_W_ERR; } if (((200 <= (ref7 = ctx.response.status) && ref7 <= 299)) && routeSuccess) { tx.status = transactionStatus.SUCCESSFUL; } if (((400 <= (ref8 = ctx.response.status) && ref8 <= 499)) && routeSuccess) { tx.status = transactionStatus.COMPLETED; } } if (!ctx.status) { tx.status = transactionStatus.COMPLETED; } logger.info("Final status for transaction " + tx._id + " : " + tx.status); return transactions.Transaction.findByIdAndUpdate(transactionId, { status: tx.status }, {}, function(err, tx) { tx.save; return callback(tx); }); } }); }; exports.koaMiddleware = function*(next) { var saveTransaction, startTime; if (statsdServer.enabled) { startTime = new Date(); } saveTransaction = Q.denodeify(exports.storeTransaction); (yield saveTransaction(this)); if (statsdServer.enabled) { sdc.timing(domain + ".messageStoreMiddleware.storeTransaction", startTime); } (yield next); if (statsdServer.enabled) { startTime = new Date(); } exports.storeResponse(this, function() {}); if (statsdServer.enabled) { return sdc.timing(domain + ".messageStoreMiddleware.storeResponse", startTime); } }; //# sourceMappingURL=messageStore.js.map