|
1 | | -'use strict'; |
2 | | - |
3 | | -let config = require('./config'); |
4 | | -let express = require('express'); |
5 | | -let morgan = require('morgan'); |
6 | | -let bodyParser = require('body-parser'); |
7 | | -let Raven = require('raven'); |
8 | | -if (config.SENTRY_DSN) { |
9 | | - Raven.config(config.SENTRY_DSN) |
10 | | - .install(); |
| 1 | +'use strict' |
| 2 | + |
| 3 | +// get configuration |
| 4 | +const { |
| 5 | + SENTRY_DSN, |
| 6 | + MAX_POST_SIZE, |
| 7 | + FALLBACK, |
| 8 | + RABBIT |
| 9 | +} = require('./config') |
| 10 | + |
| 11 | +let serviceIsAvailable = false |
| 12 | +const express = require('express') |
| 13 | +const morgan = require('morgan') |
| 14 | +const bodyParser = require('body-parser') |
| 15 | +const Raven = require('raven') |
| 16 | + |
| 17 | +//TODO Upgrade to sentry pls -- this is deprecated |
| 18 | +if (SENTRY_DSN) { |
| 19 | + Raven.config(SENTRY_DSN) |
| 20 | + .install() |
11 | 21 | } |
12 | 22 |
|
13 | | -if (config.FALLBACK) { |
14 | | - // Use var intentionally so that rabbit doesn't need to be defined |
15 | | - var rabbit = require('./rabbit'); // eslint-disable-line no-var |
16 | | -} |
| 23 | +const prom = require('./lib/prometheus') |
| 24 | +const logger = require('./lib/logger') |
| 25 | +const queue = require('./lib/queue') |
| 26 | +const ServiceError = require('./lib/ServiceError') |
| 27 | +const rabbitController = require('./lib/rabbit') |
17 | 28 |
|
18 | | -let prom = require('./prometheus'); |
19 | | - |
20 | | -let logger = require('./logger'); |
21 | | -let pubsub = require('./pubsub'); |
22 | | -let queue = require('./queue'); |
23 | | - |
24 | | -// bootstrap app |
25 | | -let app = express(); |
26 | | -app.use(morgan('dev')); |
27 | | -app.use(bodyParser.json({ limit: config.MAX_POST_SIZE })); |
28 | | -app.use(bodyParser.urlencoded({extended: false})); |
29 | | - |
30 | | -// register routes |
31 | | -app.get('/', (req, res, next) => { |
32 | | - res.json({ping: 'pong'}); |
33 | | -}); |
34 | | - |
35 | | -app.get('/healthz', (req, res, next) => { |
36 | | - res.json({ping: 'pong'}); |
37 | | -}); |
38 | | - |
39 | | -app.post('/messages/:channel', (req, res, next) => { |
40 | | - let end = prom.requestSummary.startTimer(); |
41 | | - let channel = req.params.channel; |
42 | | - prom.receiveCount.inc({channel}); |
43 | | - let messages = req.body.messages || []; |
44 | | - queue.push(publishJob(channel, messages, end)); |
45 | | - res.json({success: true}); |
46 | | -}); |
47 | | - |
48 | | - |
49 | | - /** |
50 | | - * Return a job |
51 | | - * |
52 | | - * @param {String} channel |
53 | | - * @param {[Object]} messages |
54 | | - * @param {Function} end |
55 | | - * @param {Integer} retries |
56 | | - * |
57 | | - * @return {Function} |
58 | | - */ |
59 | | -function publishJob(channel, messages, end, retries=0) { |
60 | | - return function(cb) { |
61 | | - pubsub.publish(channel, messages).then((result)=>{ |
62 | | - let errors = result.errors; |
63 | | - if(errors.length > 0) { |
64 | | - prom.publishCount.inc({state: 'failed', channel}); |
65 | | - if(config.FALLBACK && retries >= 2) { |
66 | | - end(); |
67 | | - return rabbit.publish(channel, errors); |
68 | | - } |
69 | | - retries++; |
70 | | - queue.push(publishJob(channel, errors.map((error) => error.message), end, retries)); |
71 | | - } else { |
72 | | - prom.publishCount.inc({state: 'success', channel}); |
73 | | - end(); |
74 | | - } |
75 | | - cb(); |
76 | | - }).catch((error) => { |
77 | | - cb(error); |
78 | | - }); |
79 | | - }; |
80 | | -} |
| 29 | +if (FALLBACK) rabbitController.start() |
| 30 | + |
| 31 | +const app = express() |
| 32 | + |
| 33 | +app.use(morgan('dev')) |
| 34 | +app.use(bodyParser.json({ limit: MAX_POST_SIZE })) |
| 35 | +app.use(bodyParser.urlencoded({ extended: false })) |
| 36 | + |
| 37 | +// why is this here? :shrug: |
| 38 | +app.get('/', async (req, res) => { |
| 39 | + // logger.info('ping') |
| 40 | + res.json({ ping: 'pong' }).end() |
| 41 | +}) |
| 42 | + |
| 43 | +// k8s health check endpoint |
| 44 | +app.get('/healthz', (req, res) => { |
| 45 | + if (!serviceIsAvailable) throw new ServiceError('This service is not currently accepting requests', 400) |
| 46 | + res.json({ ping: 'pong' }) |
| 47 | +} ) |
81 | 48 |
|
82 | | -// bind middleware |
83 | | -app.use((req, res, next) => { |
84 | | - let err = new Error('Not Found'); |
85 | | - err.status = 404; |
86 | | - next(err); |
87 | | -}); |
| 49 | +// handle incoming message post requests |
| 50 | +app.post('/messages/:channel', async (req, res) => { |
| 51 | + const end = prom.requestSummary.startTimer() |
| 52 | + const channel = req.params.channel |
| 53 | + const messages = req.body.messages |
88 | 54 |
|
| 55 | + // Early exit if the format is wrong |
| 56 | + if (!Array.isArray(messages)) throw new ServiceError('`messages` property is expected to be an array', 400) |
| 57 | + |
| 58 | + // Count this channel add |
| 59 | + prom.receiveCount.inc({ channel }) |
| 60 | + queue.addPublishJob(channel, messages, end) |
| 61 | + res.json({ success: true }).end() |
| 62 | +}) |
| 63 | + |
| 64 | + |
| 65 | +// Anything requests that have not been dealt with by this point is 404 |
| 66 | +app.use((req, res, next) => next(new ServiceError('Not Found', 404))) |
| 67 | + |
| 68 | +// Express Error Handler |
| 69 | +// eslint-disable-next-line no-unused-vars |
89 | 70 | app.use((err, req, res, next) => { |
90 | | - // set locals, only providing error in development |
91 | | - res.locals.message = err.message; |
92 | | - res.locals.error = req.app.get('env') === 'development' ? err : {}; |
93 | | - |
94 | | - // return a json error response |
95 | | - let status = err.status || 500; |
96 | | - res.status(status); |
97 | | - res.json({ |
98 | | - status: status, |
99 | | - message: err.message, |
100 | | - }); |
101 | | -}); |
102 | | - |
103 | | -let onExitHandler = () => { |
104 | | - logger.info('Preparing to shutdown application'); |
105 | | - |
106 | | - logger.info('Stopping queue timer'); |
107 | | - clearInterval(queue.timer); |
108 | | - |
109 | | - logger.info('Closing express server socket'); |
110 | | - // When the HTTP server closes we want to empty the job queue. |
111 | | - app.server.close(emptyQueue); |
112 | | -}; |
113 | | - |
114 | | - |
115 | | -/** |
116 | | - * Run the queue and exit if it is empty |
117 | | - */ |
118 | | -function emptyQueue() { |
119 | | - if(queue.length > 0) { |
120 | | - logger.info('Processing remaining jobs on queue'); |
121 | | - queue.start(emptyQueue); |
122 | | - } |
| 71 | + // set locals, only providing error in development |
| 72 | + res.locals.message = err.message |
| 73 | + res.locals.error = req.app.get('env') === 'development' ? err : {} |
| 74 | + |
| 75 | + // return a json error response |
| 76 | + let status = err.status || 500 |
| 77 | + res.status(status) |
| 78 | + res.json({ |
| 79 | + status, |
| 80 | + message: err.message |
| 81 | + }) |
| 82 | +}) |
| 83 | + |
| 84 | +// Graceful shutdown |
| 85 | +let exitHandler = async () => { |
| 86 | + serviceIsAvailable = false // Health endpoint will start reporting failure |
| 87 | + |
| 88 | + logger.info('Shutdown Initiated.') |
| 89 | + |
| 90 | + logger.info('Express server has shut down.') |
| 91 | + |
| 92 | + Promise.all([ |
| 93 | + queue.end(), //Empty queue |
| 94 | + rabbitController.stop(RABBIT.SHUTDOWN_WAIT) //Wait for rabbit connection to close |
| 95 | + ]).then(()=>{ |
| 96 | + logger.info('PSRP Terminating.') |
| 97 | + |
| 98 | + }).catch(()=>{}) |
123 | 99 | } |
124 | 100 |
|
125 | | -process.on('SIGTERM', () => { |
126 | | - onExitHandler(); |
127 | | -}); |
128 | | - |
129 | | -process.on('SIGINT', () => { |
130 | | - onExitHandler(); |
131 | | -}); |
| 101 | +// Make sure we exit cleanly |
| 102 | +process.on('SIGTERM', exitHandler) // regular termination signal |
| 103 | +process.on('SIGINT', exitHandler) // for ^C |
| 104 | +// process.on('SIGUSR2', exitHandler) // for nodemon during dev |
132 | 105 |
|
133 | | -module.exports = app; |
| 106 | +serviceIsAvailable = true // Health endpoint will start reporting success |
| 107 | +module.exports = app |
0 commit comments