From ca28b577a4272b77020b3333f4e48721fa1b2135 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leandro=20L=C3=B3pez?= Date: Sun, 23 Jan 2022 01:08:12 -0300 Subject: [PATCH] chore: improve `/healthz` endpoint performance (#2014) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add benchmark for /healthz endpoint This benchmark will measure not only speed but also how much memory each request to /healthz allocate. I'm adding the benchmark to have a baseline to compare. Signed-off-by: Leandro López (inkel) * Hardcode /healthz body into a variable We know it will always be this value, there's no need to import and call json.MarshalIndent. Signed-off-by: Leandro López (inkel) * Initialize /healthz body only once Signed-off-by: Leandro López (inkel) --- server/server.go | 17 +++++------------ server/server_test.go | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/server/server.go b/server/server.go index aab01de64..8c4aac195 100644 --- a/server/server.go +++ b/server/server.go @@ -17,7 +17,6 @@ package server import ( "context" - "encoding/json" "flag" "fmt" "log" @@ -899,20 +898,14 @@ func mkSubDir(parentDir string, subDir string) (string, error) { // Healthz returns the health check response. It always returns a 200 currently. func (s *Server) Healthz(w http.ResponseWriter, _ *http.Request) { - data, err := json.MarshalIndent(&struct { - Status string `json:"status"` - }{ - Status: "ok", - }, "", " ") - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintf(w, "Error creating status json response: %s", err) - return - } w.Header().Set("Content-Type", "application/json") - w.Write(data) // nolint: errcheck + w.Write(healthzData) // nolint: errcheck } +var healthzData = []byte(`{ + "status": "ok" +}`) + // ParseAtlantisURL parses the user-passed atlantis URL to ensure it is valid // and we can use it in our templates. // It removes any trailing slashes from the path so we can concatenate it diff --git a/server/server_test.go b/server/server_test.go index 4ed72785a..1af422be3 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -147,6 +147,25 @@ func TestHealthz(t *testing.T) { }`, string(body)) } +type mockRW struct{} + +var _ http.ResponseWriter = mockRW{} +var mh = http.Header{} + +func (w mockRW) WriteHeader(int) {} +func (w mockRW) Write([]byte) (int, error) { return 0, nil } +func (w mockRW) Header() http.Header { return mh } + +var w = mockRW{} +var s = &server.Server{} + +func BenchmarkHealthz(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + s.Healthz(w, nil) + } +} + func TestParseAtlantisURL(t *testing.T) { cases := []struct { In string