From 9b026d1bcb9d05c6ca5452d8f1e6f52e9f925a42 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Julian=20B=C3=A4ume?= <julian.baeume@open-xchange.com>
Date: Fri, 1 Oct 2021 16:29:24 +0200
Subject: [PATCH] move cache warmup into readiness check

this will mark the pod "ready", once the cache is warm.
This will remove the penality for the very first to this service, because
it will not receive any traffic until the cache is warm.
---
 spec/file_caching_test.js |  1 +
 src/createApp.js          | 11 +++++++++--
 2 files changed, 10 insertions(+), 2 deletions(-)

diff --git a/spec/file_caching_test.js b/spec/file_caching_test.js
index 5dfc979..c545637 100644
--- a/spec/file_caching_test.js
+++ b/spec/file_caching_test.js
@@ -44,6 +44,7 @@ describe('File caching service', () => {
       '/main.css': (req, res) => res.setHeader('content-type', 'text/css').status(200).send('.foo { color: #000; }')
 
     })
+    await request(app).get('/ready')
   })
 
   afterEach(() => {
diff --git a/src/createApp.js b/src/createApp.js
index c9d3ab2..f68d9b3 100644
--- a/src/createApp.js
+++ b/src/createApp.js
@@ -35,6 +35,15 @@ export function createApp () {
   const httpLogger = pinoHttp({ logger, autoLogging: { ignorePaths } })
 
   const healthCheck = new health.HealthChecker()
+  const readinessCheck = new health.ReadinessCheck('getDependencies', async function () {
+    try {
+      await getDependencies()
+    } catch (e) {
+      logger.error(`Failed to get dependencies: ${e.message}`)
+      throw e
+    }
+  })
+  healthCheck.registerReadinessCheck(readinessCheck)
 
   // Application-level middleware
   app.use(httpLogger)
@@ -70,14 +79,12 @@ export function createApp () {
   })
 
   app.get('/', async (req, res, next) => {
-    await getDependencies()
     const { 'content-type': contentType, content } = fileCache.get('/index.html')
     if (content) return res.setHeader('content-type', contentType).status(200).send(content)
     next()
   })
 
   app.use(async (req, res, next) => {
-    await getDependencies()
     const { 'content-type': contentType, content } = fileCache.get(req.path)
     if (content) return res.setHeader('content-type', contentType).status(200).send(content)
     next()
-- 
GitLab