forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
warm-server.js
82 lines (66 loc) · 2.11 KB
/
warm-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
const statsd = require('./statsd')
const { loadPages, loadPageMap } = require('./pages')
const loadRedirects = require('./redirects/precompile')
const loadSiteData = require('./site-data')
const loadSiteTree = require('./site-tree')
// Instrument these functions so that
// it's wrapped in a timer that reports to Datadog
const dog = {
loadPages: statsd.timer(loadPages, 'load_pages'),
loadPageMap: statsd.timer(loadPageMap, 'load_page_map'),
loadRedirects: statsd.timer(loadRedirects, 'load_redirects'),
loadSiteData: statsd.timer(loadSiteData, 'load_site_data'),
loadSiteTree: statsd.asyncTimer(loadSiteTree, 'load_site_tree')
}
// For local caching
let pageList, pageMap, site, redirects, siteTree
function isFullyWarmed () {
// NOTE: Yes, `pageList` is specifically excluded here as it is transient data
const fullyWarmed = !!(pageMap && site && redirects && siteTree)
return fullyWarmed
}
function getWarmedCache () {
return {
pages: pageMap,
site,
redirects,
siteTree
}
}
async function warmServer () {
const startTime = Date.now()
if (process.env.NODE_ENV !== 'test') {
console.log('Priming context information...')
}
if (!pageList) {
pageList = dog.loadPages()
}
if (!site) {
site = dog.loadSiteData()
}
if (!pageMap) {
pageMap = dog.loadPageMap(pageList)
}
if (!redirects) {
redirects = dog.loadRedirects(pageList, pageMap)
}
if (!siteTree) {
siteTree = await dog.loadSiteTree(pageMap, site, redirects)
}
if (process.env.NODE_ENV !== 'test') {
console.log(`Context primed in ${Date.now() - startTime} ms`)
}
return getWarmedCache()
}
// Instrument the `warmServer` function so that
// it's wrapped in a timer that reports to Datadog
dog.warmServer = statsd.asyncTimer(warmServer, 'warm_server')
// We only want statistics if the priming needs to occur, so let's wrap the
// real method and return early [without statistics] whenever possible
module.exports = async function warmServerWrapper () {
// Bail out early if everything is properly ready to use
if (isFullyWarmed()) {
return getWarmedCache()
}
return dog.warmServer()
}