/
health.go
96 lines (79 loc) · 2.24 KB
/
health.go
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package horizon
import (
"context"
"encoding/json"
"net/http"
"sync"
"time"
"github.com/TosinShada/stellar-core/protocols/stellarcore"
"github.com/TosinShada/stellar-core/support/clock"
"github.com/TosinShada/stellar-core/support/db"
"github.com/TosinShada/stellar-core/support/log"
)
const (
dbPingTimeout = 5 * time.Second
infoRequestTimeout = 5 * time.Second
healthCacheTTL = 500 * time.Millisecond
)
var healthLogger = log.WithField("service", "healthCheck")
type stellarCoreClient interface {
Info(ctx context.Context) (*stellarcore.InfoResponse, error)
}
type healthCache struct {
response healthResponse
lastUpdate time.Time
ttl time.Duration
clock clock.Clock
lock sync.Mutex
}
func (h *healthCache) get(runCheck func() healthResponse) healthResponse {
h.lock.Lock()
defer h.lock.Unlock()
if h.clock.Now().Sub(h.lastUpdate) > h.ttl {
h.response = runCheck()
h.lastUpdate = h.clock.Now()
}
return h.response
}
func newHealthCache(ttl time.Duration) *healthCache {
return &healthCache{ttl: ttl}
}
type healthCheck struct {
session db.SessionInterface
ctx context.Context
core stellarCoreClient
cache *healthCache
}
type healthResponse struct {
DatabaseConnected bool `json:"database_connected"`
CoreUp bool `json:"core_up"`
CoreSynced bool `json:"core_synced"`
}
func (h healthCheck) runCheck() healthResponse {
response := healthResponse{
DatabaseConnected: true,
CoreUp: true,
CoreSynced: true,
}
if err := h.session.Ping(h.ctx, dbPingTimeout); err != nil {
healthLogger.Warnf("could not ping db: %s", err)
response.DatabaseConnected = false
}
if resp, err := h.core.Info(h.ctx); err != nil {
healthLogger.Warnf("request to stellar core failed: %s", err)
response.CoreUp = false
response.CoreSynced = false
} else {
response.CoreSynced = resp.IsSynced()
}
return response
}
func (h healthCheck) ServeHTTP(w http.ResponseWriter, r *http.Request) {
response := h.cache.get(h.runCheck)
if !response.DatabaseConnected || !response.CoreSynced || !response.CoreUp {
w.WriteHeader(http.StatusServiceUnavailable)
}
if err := json.NewEncoder(w).Encode(response); err != nil {
healthLogger.Warnf("could not write response: %s", err)
}
}