-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
server.js
237 lines (204 loc) · 5.95 KB
/
server.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
'use strict'
const path = require('path')
const Joi = require('joi')
const Camp = require('camp')
const makeBadge = require('../gh-badges/lib/make-badge')
const GithubConstellation = require('../services/github/github-constellation')
const { loadServiceClasses } = require('../services')
const analytics = require('./analytics')
const { makeBadgeData } = require('./badge-data')
const log = require('./log')
const { staticBadgeUrl } = require('./make-badge-url')
const suggest = require('./suggest')
const sysMonitor = require('./sys/monitor')
const PrometheusMetrics = require('./sys/prometheus-metrics')
const { makeSend } = require('./result-sender')
const { handleRequest, clearRequestCache } = require('./request-handler')
const { clearRegularUpdateCache } = require('./regular-update')
const optionalUrl = Joi.string().uri({ scheme: ['http', 'https'] })
const requiredUrl = optionalUrl.required()
const configSchema = Joi.object({
bind: {
port: Joi.number()
.port()
.required(),
address: Joi.alternatives()
.try(
Joi.string()
.ip()
.required(),
Joi.string()
.hostname()
.required()
)
.required(),
},
metrics: {
prometheus: {
enabled: Joi.boolean().required(),
allowedIps: Joi.string(),
},
},
ssl: {
isSecure: Joi.boolean().required(),
key: Joi.string(),
cert: Joi.string(),
},
baseUri: requiredUrl,
redirectUrl: optionalUrl,
cors: {
allowedOrigin: Joi.array()
.items(optionalUrl)
.required(),
},
persistence: {
dir: Joi.string().required(),
redisUrl: optionalUrl,
},
services: {
github: {
baseUri: requiredUrl,
debug: {
enabled: Joi.boolean().required(),
intervalSeconds: Joi.number()
.integer()
.min(1),
},
},
trace: Joi.boolean().required(),
},
profiling: {
makeBadge: Joi.boolean().required(),
},
cacheHeaders: {
defaultCacheLengthSeconds: Joi.number().integer(),
},
rateLimit: Joi.boolean().required(),
handleInternalErrors: Joi.boolean().required(),
}).required()
module.exports = class Server {
constructor(config) {
Joi.assert(config, configSchema)
this.config = config
this.githubConstellation = new GithubConstellation({
persistence: config.persistence,
service: config.services.github,
})
this.metrics = new PrometheusMetrics(config.metrics.prometheus)
}
get baseUrl() {
return this.config.baseUri
}
registerErrorHandlers() {
const { camp } = this
camp.notfound(/\.(svg|png|gif|jpg|json)/, (query, match, end, request) => {
const format = match[1]
const badgeData = makeBadgeData('404', query)
badgeData.text[1] = 'badge not found'
badgeData.colorscheme = 'red'
// Add format to badge data.
badgeData.format = format
const svg = makeBadge(badgeData)
makeSend(format, request.res, end)(svg)
})
camp.notfound(/.*/, (query, match, end, request) => {
end(null, { template: '404.html' })
})
}
registerServices() {
const { config, camp } = this
const { apiProvider: githubApiProvider } = this.githubConstellation
loadServiceClasses().forEach(serviceClass =>
serviceClass.register(
{ camp, handleRequest, githubApiProvider },
{
handleInternalErrors: config.handleInternalErrors,
cacheHeaders: config.cacheHeaders,
profiling: config.profiling,
}
)
)
}
registerRedirects() {
const { config, camp } = this
// Any badge, old version. This route must be registered last.
camp.route(/^\/([^/]+)\/(.+).png$/, (queryParams, match, end, ask) => {
const [, label, message] = match
const { color } = queryParams
const redirectUrl = staticBadgeUrl({
label,
message,
color,
format: 'png',
})
ask.res.statusCode = 301
ask.res.setHeader('Location', redirectUrl)
// The redirect is permanent.
const cacheDuration = (365 * 24 * 3600) | 0 // 1 year
ask.res.setHeader('Cache-Control', `max-age=${cacheDuration}`)
ask.res.end()
})
if (config.redirectUrl) {
camp.route(/^\/$/, (data, match, end, ask) => {
ask.res.statusCode = 302
ask.res.setHeader('Location', config.redirectUrl)
ask.res.end()
})
}
}
async start() {
const {
bind: { port, address: hostname },
ssl: { isSecure: secure, cert, key },
cors: { allowedOrigin },
baseUri,
rateLimit,
} = this.config
log(`Server is starting up: ${baseUri}`)
const camp = (this.camp = Camp.start({
documentRoot: path.join(__dirname, '..', 'public'),
port,
hostname,
secure,
cert,
key,
}))
analytics.load()
analytics.scheduleAutosaving()
analytics.setRoutes(camp)
this.cleanupMonitor = sysMonitor.setRoutes({ rateLimit }, camp)
const { githubConstellation, metrics } = this
githubConstellation.initialize(camp)
metrics.initialize(camp)
const { apiProvider: githubApiProvider } = this.githubConstellation
suggest.setRoutes(allowedOrigin, githubApiProvider, camp)
this.registerErrorHandlers()
this.registerServices()
this.registerRedirects()
await new Promise(resolve => camp.on('listening', () => resolve()))
}
static resetGlobalState() {
// This state should be migrated to instance state. When possible, do not add new
// global state.
clearRequestCache()
clearRegularUpdateCache()
}
reset() {
this.constructor.resetGlobalState()
}
async stop() {
if (this.camp) {
await new Promise(resolve => this.camp.close(resolve))
this.camp = undefined
}
if (this.cleanupMonitor) {
this.cleanupMonitor()
this.cleanupMonitor = undefined
}
if (this.githubConstellation) {
await this.githubConstellation.stop()
this.githubConstellation = undefined
}
analytics.cancelAutosaving()
}
}