diff --git a/src/files.js b/src/files.js index c9f27e06cdff8438b51a3acdac5dedb38b719f00..289790596f004a7d5c70ffec119395780854618e 100644 --- a/src/files.js +++ b/src/files.js @@ -84,3 +84,21 @@ export function getFile ({ version, path }) { return fetchFileWithHeaders({ version, path }) }) } + +export async function warmCache ({ version }) { + const start = +new Date() + logger.info('[File] start warming up the cache') + const viteManifests = await getViteManifests({ version }) + + for (const key of Object.keys(viteManifests)) { + const path = `/${viteManifests[key].file}` + if (!path) continue + try { + await getFile({ version, path }) + } catch (err) { + logger.info(`[File] could not prefetch file ${path}`) + } + } + + logger.info(`[File] finished warming up the cache in ${Math.floor((+new Date() - start) / 1000)}s`) +} diff --git a/src/index.js b/src/index.js index a1419b0bbe62274de085afdac890b84bf91c5e71..6309e12e1c95626c83fadfc236df0796d2c853a9 100644 --- a/src/index.js +++ b/src/index.js @@ -8,6 +8,7 @@ import { configMap } from './configMap.js' import * as redis from './redis.js' import lightshipCjs from 'lightship' import { createMetricsServer } from './metrics.js' +import { warmCache } from './files.js' config() @@ -26,6 +27,13 @@ app.addHook('onReady', () => { lightship.signalReady() }) +app.addHook('onReady', () => { + // don't block the onReady hook + getLatestVersion() + .then(version => warmCache({ version })) + .catch(err => logger.error(err)) +}) + // Binds and listens for connections on the specified host and port app.listen({ host: '::', port: Number(process.env.PORT) }) diff --git a/src/version.js b/src/version.js index e87b7da3632390c0292009f778a224addb5199dc..4103c7de531e39956e08041507d2d32d2b083160 100644 --- a/src/version.js +++ b/src/version.js @@ -5,6 +5,7 @@ import * as cache from './cache.js' import * as redis from './redis.js' import { Gauge } from 'prom-client' import { getViteManifests } from './manifests.js' +import { warmCache } from './files.js' let latestVersion @@ -80,6 +81,7 @@ export function registerLatestVersionListener (client) { await configMap.load() versionUpdateGauge.setToCurrentTime({ version }) cache.clear() + warmCache({ version }).catch(err => logger.error(err)) latestVersion = version }) } @@ -121,6 +123,7 @@ export async function updateVersionProcessor () { // if redis is disabled, this will only be trigger by a setInterval and not from a redis event logger.info('[Version] Clear local cache due to version update.') cache.clear() + warmCache({ version: fetchedVersion }).catch(err => logger.error(err)) latestVersion = fetchedVersion } return latestVersion