forked from badges/shields
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
335 lines (299 loc) · 9.53 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
'use strict'
const { DOMParser } = require('xmldom')
const jp = require('jsonpath')
const path = require('path')
const xpath = require('xpath')
const yaml = require('js-yaml')
const Raven = require('raven')
const serverSecrets = require('./lib/server-secrets')
Raven.config(process.env.SENTRY_DSN || serverSecrets.sentry_dsn).install()
Raven.disableConsoleAlerts()
const { loadServiceClasses } = require('./services')
const { checkErrorResponse } = require('./lib/error-helper')
const analytics = require('./lib/analytics')
const config = require('./lib/server-config')
const GithubConstellation = require('./services/github/github-constellation')
const sysMonitor = require('./lib/sys/monitor')
const log = require('./lib/log')
const { makeMakeBadgeFn } = require('./lib/make-badge')
const { QuickTextMeasurer } = require('./lib/text-measurer')
const suggest = require('./lib/suggest')
const {
makeColorB,
makeLabel: getLabel,
makeBadgeData: getBadgeData,
setBadgeColor,
} = require('./lib/badge-data')
const {
makeHandleRequestFn,
clearRequestCache,
} = require('./lib/request-handler')
const { clearRegularUpdateCache } = require('./lib/regular-update')
const { makeSend } = require('./lib/result-sender')
const { escapeFormat } = require('./lib/path-helpers')
const serverStartTime = new Date(new Date().toGMTString())
const camp = require('camp').start({
documentRoot: path.join(__dirname, 'public'),
port: config.bind.port,
hostname: config.bind.address,
secure: config.ssl.isSecure,
cert: config.ssl.cert,
key: config.ssl.key,
})
const githubConstellation = new GithubConstellation({
persistence: config.persistence,
service: config.services.github,
})
const { apiProvider: githubApiProvider } = githubConstellation
function reset() {
clearRequestCache()
clearRegularUpdateCache()
}
async function stop() {
await githubConstellation.stop()
analytics.cancelAutosaving()
return new Promise(resolve => {
camp.close(resolve)
})
}
module.exports = {
camp,
reset,
stop,
}
log(`Server is starting up: ${config.baseUri}`)
let measurer
try {
measurer = new QuickTextMeasurer(config.font.path, config.font.fallbackPath)
} catch (e) {
console.log(`Unable to load fallback font. Using Helvetica-Bold instead.`)
measurer = new QuickTextMeasurer('Helvetica')
}
const makeBadge = makeMakeBadgeFn(measurer)
const cache = makeHandleRequestFn(makeBadge)
analytics.load()
analytics.scheduleAutosaving()
analytics.setRoutes(camp)
if (serverSecrets && serverSecrets.shieldsSecret) {
sysMonitor.setRoutes(camp)
}
githubConstellation.initialize(camp)
suggest.setRoutes(config.cors.allowedOrigin, githubApiProvider, camp)
camp.notfound(/\.(svg|png|gif|jpg|json)/, (query, match, end, request) => {
const format = match[1]
const badgeData = getBadgeData('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' })
})
// Vendors.
loadServiceClasses().forEach(serviceClass =>
serviceClass.register(
{ camp, handleRequest: cache, githubApiProvider },
{ handleInternalErrors: config.handleInternalErrors }
)
)
// User defined sources - JSON response
camp.route(
/^\/badge\/dynamic\/(json|xml|yaml)\.(svg|png|gif|jpg|json)$/,
cache({
queryParams: ['uri', 'url', 'query', 'prefix', 'suffix'],
handler: function(query, match, sendBadge, request) {
const type = match[1]
const format = match[2]
const prefix = query.prefix || ''
const suffix = query.suffix || ''
const pathExpression = query.query
let requestOptions = {}
const badgeData = getBadgeData('custom badge', query)
if ((!query.uri && !query.url) || !query.query) {
setBadgeColor(badgeData, 'red')
badgeData.text[1] = !query.query
? 'no query specified'
: 'no url specified'
sendBadge(format, badgeData)
return
}
let url
try {
url = encodeURI(decodeURIComponent(query.url || query.uri))
} catch (e) {
setBadgeColor(badgeData, 'red')
badgeData.text[1] = 'malformed url'
sendBadge(format, badgeData)
return
}
switch (type) {
case 'json':
requestOptions = {
headers: {
Accept: 'application/json',
},
json: true,
}
break
case 'xml':
requestOptions = {
headers: {
Accept: 'application/xml, text/xml',
},
}
break
case 'yaml':
requestOptions = {
headers: {
Accept:
'text/x-yaml, text/yaml, application/x-yaml, application/yaml, text/plain',
},
}
break
}
request(url, requestOptions, (err, res, data) => {
try {
if (
checkErrorResponse(badgeData, err, res, {
404: 'resource not found',
})
) {
return
}
badgeData.colorscheme = 'brightgreen'
let innerText = []
switch (type) {
case 'json':
data = typeof data === 'object' ? data : JSON.parse(data)
data = jp.query(data, pathExpression)
if (!data.length) {
throw Error('no result')
}
innerText = data
break
case 'xml':
data = new DOMParser().parseFromString(data)
data = xpath.select(pathExpression, data)
if (!data.length) {
throw Error('no result')
}
data.forEach((i, v) => {
innerText.push(
pathExpression.indexOf('@') + 1 ? i.value : i.firstChild.data
)
})
break
case 'yaml':
data = yaml.safeLoad(data)
data = jp.query(data, pathExpression)
if (!data.length) {
throw Error('no result')
}
innerText = data
break
}
badgeData.text[1] =
(prefix || '') + innerText.join(', ') + (suffix || '')
} catch (e) {
setBadgeColor(badgeData, 'lightgrey')
badgeData.text[1] = e.message
} finally {
sendBadge(format, badgeData)
}
})
},
})
)
// Any badge.
camp.route(
/^\/(:|badge\/)(([^-]|--)*?)-?(([^-]|--)*)-(([^-]|--)+)\.(svg|png|gif|jpg)$/,
(data, match, end, ask) => {
const subject = escapeFormat(match[2])
const status = escapeFormat(match[4])
const color = escapeFormat(match[6])
const format = match[8]
analytics.noteRequest(data, match)
// Cache management - the badge is constant.
const cacheDuration = (3600 * 24 * 1) | 0 // 1 day.
ask.res.setHeader('Cache-Control', 'max-age=' + cacheDuration)
if (+new Date(ask.req.headers['if-modified-since']) >= +serverStartTime) {
ask.res.statusCode = 304
ask.res.end() // not modified.
return
}
ask.res.setHeader('Last-Modified', serverStartTime.toGMTString())
// Badge creation.
try {
const badgeData = getBadgeData(subject, data)
badgeData.text[0] = getLabel(undefined, { label: subject })
badgeData.text[1] = status
badgeData.colorB = makeColorB(color, data)
badgeData.template = data.style
if (config.profiling.makeBadge) {
console.time('makeBadge total')
}
const svg = makeBadge(badgeData)
if (config.profiling.makeBadge) {
console.timeEnd('makeBadge total')
}
makeSend(format, ask.res, end)(svg)
} catch (e) {
log.error(e.stack)
const svg = makeBadge({
text: ['error', 'bad badge'],
colorscheme: 'red',
})
makeSend(format, ask.res, end)(svg)
}
}
)
// Production cache debugging.
let bitFlip = false
camp.route(/^\/flip\.svg$/, (data, match, end, ask) => {
const cacheSecs = 60
ask.res.setHeader('Cache-Control', 'max-age=' + cacheSecs)
const reqTime = new Date()
const date = new Date(+reqTime + cacheSecs * 1000).toGMTString()
ask.res.setHeader('Expires', date)
const badgeData = getBadgeData('flip', data)
bitFlip = !bitFlip
badgeData.text[1] = bitFlip ? 'on' : 'off'
badgeData.colorscheme = bitFlip ? 'brightgreen' : 'red'
const svg = makeBadge(badgeData)
makeSend('svg', ask.res, end)(svg)
})
// Any badge, old version.
camp.route(/^\/([^/]+)\/(.+).png$/, (data, match, end, ask) => {
const subject = match[1]
const status = match[2]
const color = data.color
// Cache management - the badge is constant.
const cacheDuration = (3600 * 24 * 1) | 0 // 1 day.
ask.res.setHeader('Cache-Control', 'max-age=' + cacheDuration)
if (+new Date(ask.req.headers['if-modified-since']) >= +serverStartTime) {
ask.res.statusCode = 304
ask.res.end() // not modified.
return
}
ask.res.setHeader('Last-Modified', serverStartTime.toGMTString())
// Badge creation.
try {
const badgeData = { text: [subject, status] }
badgeData.colorscheme = color
const svg = makeBadge(badgeData)
makeSend('png', ask.res, end)(svg)
} catch (e) {
const svg = makeBadge({ text: ['error', 'bad badge'], colorscheme: 'red' })
makeSend('png', ask.res, end)(svg)
}
})
if (config.redirectUri) {
camp.route(/^\/$/, (data, match, end, ask) => {
ask.res.statusCode = 302
ask.res.setHeader('Location', config.redirectUri)
ask.res.end()
})
}