|
| 1 | +const statsd = require('./statsd') |
| 2 | +const loadPageData = require('./page-data') |
| 3 | +const loadRedirects = require('./redirects/precompile') |
| 4 | +const loadSiteData = require('./site-data') |
| 5 | + |
| 6 | +// Instrument these functions so that |
| 7 | +// it's wrapped in a timer that reports to Datadog |
| 8 | +const dog = { |
| 9 | + loadPageData: statsd.asyncTimer(loadPageData, 'load_page_data'), |
| 10 | + loadRedirects: statsd.asyncTimer(loadRedirects, 'load_redirects'), |
| 11 | + loadSiteData: statsd.timer(loadSiteData, 'load_site_data') |
| 12 | +} |
| 13 | + |
| 14 | +// For local caching |
| 15 | +let pageList, pageMap, site, redirects, siteTree |
| 16 | + |
| 17 | +function isFullyWarmed () { |
| 18 | + // NOTE: Yes, `pageList` is specifically excluded here as it is transient data |
| 19 | + const fullyWarmed = !!(pageMap && site && redirects && siteTree) |
| 20 | + return fullyWarmed |
| 21 | +} |
| 22 | + |
| 23 | +function getWarmedCache () { |
| 24 | + return { |
| 25 | + pages: pageMap, |
| 26 | + site, |
| 27 | + redirects, |
| 28 | + siteTree |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +async function warmServer () { |
| 33 | + const startTime = Date.now() |
| 34 | + |
| 35 | + if (process.env.NODE_ENV !== 'test') { |
| 36 | + console.log('Priming context information...') |
| 37 | + } |
| 38 | + |
| 39 | + if (!siteTree) { |
| 40 | + const pageData = await dog.loadPageData() |
| 41 | + siteTree = pageData.siteTree |
| 42 | + pageList = pageData.pageList |
| 43 | + pageMap = pageData.pageMap |
| 44 | + } |
| 45 | + |
| 46 | + if (!site) { |
| 47 | + site = dog.loadSiteData() |
| 48 | + } |
| 49 | + |
| 50 | + if (!redirects) { |
| 51 | + redirects = await dog.loadRedirects(pageList) |
| 52 | + } |
| 53 | + |
| 54 | + if (process.env.NODE_ENV !== 'test') { |
| 55 | + console.log(`Context primed in ${Date.now() - startTime} ms`) |
| 56 | + } |
| 57 | + |
| 58 | + return getWarmedCache() |
| 59 | +} |
| 60 | + |
| 61 | +// Instrument the `warmServer` function so that |
| 62 | +// it's wrapped in a timer that reports to Datadog |
| 63 | +dog.warmServer = statsd.asyncTimer(warmServer, 'warm_server') |
| 64 | + |
| 65 | +// We only want statistics if the priming needs to occur, so let's wrap the |
| 66 | +// real method and return early [without statistics] whenever possible |
| 67 | +module.exports = async function warmServerWrapper () { |
| 68 | + // Bail out early if everything is properly ready to use |
| 69 | + if (isFullyWarmed()) { |
| 70 | + return getWarmedCache() |
| 71 | + } |
| 72 | + |
| 73 | + return dog.warmServer() |
| 74 | +} |
0 commit comments