forked from cnnlabs/cnn-hapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
210 lines (177 loc) · 6.21 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
'use strict';
const hapi = require('hapi'),
Hoek = require('hoek'),
robots = require('./lib/hapi/robots'),
cleanName = require('./lib/clean-name');
require('isomorphic-fetch');
let setupHealthCheck = function (request, reply) {
let payload,
response,
checks = request.server.app.__healthchecks.map(function (check) {
return check.getStatus();
});
if (checks.length === 0) {
checks.push({
name: 'App has no healthchecks',
ok: false,
severity: 3,
businessImpact: 'If this application encounters any problems, nobody will be alerted and it probably will not get fixed.',
technicalSummary: 'This app has no healthchecks set up',
panicGuide: 'Don\'t Panic',
lastUpdated: new Date()
});
}
if (request.params[0]) {
checks.forEach(function (check) {
if (check.severity <= Number(request.params.checknumber) && check.ok === false) {
reply.code(500);
}
});
}
//response.send();
payload = JSON.stringify({
schemaVersion: 1,
name: `CNN-${request.app.__name}`,
description: request.app.__description,
checks: checks
}, undefined, 2);
response = reply(payload);
response.header('Cache-Control', 'private, no-cache, max-age=0');
response.header('Content-Type', 'application/json');
},
metricsProvider = {};
/**
* Set up cache control headers
* @private
* @param {object} request - Request object
* @param {object} headers - The cache control headers to set
*/
function setCacheControlHeaders(request, headers) {
let surrogateControl = headers.surrogateCacheControl ? headers.surrogateCacheControl : false,
cacheControl = headers.cacheControlHeader ? headers.cacheControlHeader : false;
if (typeof request.response === 'object' &&
request.response !== null &&
typeof request.response.header === 'function') {
if (typeof surrogateControl === 'string') {
request.response.header('Surrogate-Control', surrogateControl);
}
if (typeof cacheControl === 'string') {
request.response.header('Cache-Control', cacheControl);
}
}
}
module.exports = function (options) {
let packageJson = {},
metricOptions = {flushEvery: 6 * 1000},
defaults = {
port: 3000,
withFlags: true,
withSwagger: false,
withHandlebars: true,
metrics: {provider: require('cnn-metrics'), options: metricOptions},
withBackendAuthentication: true,
healthChecks: []
},
port = process.env.PORT || options.port,
environment = process.env.NODE_ENV || process.env.ENVIRONMENT || '',
server = new hapi.Server(),
name = options.name,
description = '',
directory = options.directory || process.cwd(),
actualAppStart,
cacheControlHeader = process.env.CACHE_CONTROL || options.maxAge || 'max-age=60', // Default cache time is 60 seconds
surrogateControlHeader = process.env.SURROGATE_CACHE_CONTROL || options.surrogateCacheControl || 'max-age=360, stale-while-revalidate=60, stale-if-error=86400',
cacheHeaders = {
cacheControlHeader: cacheControlHeader,
surrogateCacheControl: surrogateControlHeader
};
options = options || {};
options = Hoek.applyToDefaults(defaults, options);
server.connection({port: port});
if (!name) {
try {
packageJson = require(`${directory}/package.json`);
name = packageJson.name;
description = packageJson.description;
} catch (e) {
// No problem
}
}
if (!name) {
throw new Error('Please specify an application name');
}
server.app.__name = name = cleanName(name);
server.app.__environment = environment;
server.app.__isProduction = environment.toUpperCase() === 'PRODUCTION';
server.app.__rootDirectory = directory;
server.app.__description = description;
server.app.__healthchecks = options.healthChecks;
try {
server.app.__version = require(`${directory}/public/__about.json`).appVersion;
} catch (e) {
//Its OK
}
if (options.metrics) {
options.metrics.provider.init({app: name, flushEvery: options.metrics.options.flushEvery});
metricsProvider = options.metrics.provider;
}
server.register(require('inert'), () => {});
if (options.withSwagger) {
server.register(require('vision'), () => {});
server.register({
register: require('hapi-swagger'),
options: {
info: {
title: options.name,
description: options.description
}
}
});
}
if (options.metrics.provider) {
server.register({
register: require('./lib/plugins/metrics'),
options: {
message: 'hello',
metrics: options.metrics.provider
}
});
}
server.route({
method: 'GET',
path: '/robots.txt',
handler: robots
});
server.route({
method: 'GET',
path: '/__whatami',
handler: function (request, reply) {
reply().code(418);
}
});
server.route({
method: 'GET',
path: '/_imgood',
handler: (request, reply) => reply(200)
});
server.route({
method: 'GET',
path: '/__health/{checknumber?}',
handler: setupHealthCheck
});
server.ext({
type: 'onPreResponse',
method: function (request, reply) {
setCacheControlHeaders(request, cacheHeaders);
return reply.continue();
}
});
actualAppStart = server.start;
server.start = function () {
console.log(`Listening on ${port}`);
actualAppStart.apply(this, arguments);
};
return server;
};
module.exports.services = metricsProvider.services;
module.exports.metrics = metricsProvider;