serverapm.js 1.68 KB
const lineparse = require('../lib/line-parse');
const bb = require('bluebird');

const logger = global.yoho.logger;

const {
    handleErrorReport,
    handleProcessInfo,
    handleWebServerDuration
} = require('./serverapm-service');

const riskService = require('./risk-service');
const handleRisk = riskService();

const server = {
    async handle(data) {
        try {
            let msgs = lineparse.parse(data);

            await bb.map(msgs, async(m) => {
                if (!m.measurement) {
                    return;
                }

                switch (m.measurement) {
                    case 'web-server-duration': {
                        handleWebServerDuration(m);

                        if (m.tags.type === 'route') {
                            await handleRisk(m);
                        }
                        break;
                    }
                    case 'error-report': {
                        handleErrorReport(m);
                        break;
                    }
                    case 'process-info': {
                        handleProcessInfo(m);
                        break;
                    }
                    default: {
                        logger.error('[server] handle ERROR [%s]', JSON.stringify(m));
                        break;
                    }
                }

            }, {concurrency: 2});

            logger.debug('[server] handle OK [%j]', data);
        } catch (e) {
            logger.error('[server] handle ERROR [%s]', e);
        }
    }
};

module.exports = function(req, res) {
    let data = req.body || ' ';

    server.handle(data).catch(err => {
        logger.error(err);
    });
    res.status(204).json();
};