Skip to content

Commit

Permalink
feat: liveness and readiness probes (#6)
Browse files Browse the repository at this point in the history
Signed-off-by: Carlos Alexandro Becker <[email protected]>
  • Loading branch information
caarlos0 authored Aug 2, 2024
1 parent 4ea50ae commit 009148c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
5 changes: 5 additions & 0 deletions internal/proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,13 @@ type Proxy struct {
mu sync.Mutex
servers []*Server

initialized atomic.Bool
shuttingDown atomic.Bool
}

func (p *Proxy) Ready() bool { return p.initialized.Load() }
func (p *Proxy) Live() bool { return !p.shuttingDown.Load() && p.initialized.Load() }

func (p *Proxy) Stats() []ServerStat {
var result []ServerStat
for _, s := range p.servers {
Expand Down Expand Up @@ -120,6 +124,7 @@ func (p *Proxy) update(rpcs []seed.RPC) error {
})

slog.Info("updated server list", "total", len(p.servers))
p.initialized.Store(true)
return nil
}

Expand Down
10 changes: 10 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ func main() {
indexTpl := template.Must(template.New("stats").Parse(string(index)))

m := http.NewServeMux()
m.Handle("/health/ready", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !proxyHandler.Ready() {
w.WriteHeader(http.StatusServiceUnavailable)
}
}))
m.Handle("/health/live", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !proxyHandler.Live() {
w.WriteHeader(http.StatusServiceUnavailable)
}
}))
m.Handle("/rpc", proxyHandler)
m.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := indexTpl.Execute(w, proxyHandler.Stats()); err != nil {
Expand Down

0 comments on commit 009148c

Please sign in to comment.