-
Notifications
You must be signed in to change notification settings - Fork 151
/
health.go
76 lines (62 loc) · 1.61 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
package health
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"time"
"github.com/hatchet-dev/hatchet/internal/msgqueue"
"github.com/hatchet-dev/hatchet/internal/repository"
)
type Health struct {
ready bool
repository repository.EngineRepository
queue msgqueue.MessageQueue
}
func New(prisma repository.EngineRepository, queue msgqueue.MessageQueue) *Health {
return &Health{
repository: prisma,
queue: queue,
}
}
func (h *Health) SetReady(ready bool) {
h.ready = ready
}
func (h *Health) Start() (func() error, error) {
mux := http.NewServeMux()
mux.HandleFunc("/live", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
mux.HandleFunc("/ready", func(w http.ResponseWriter, r *http.Request) {
if !h.ready || !h.queue.IsReady() || !h.repository.Health().IsHealthy() || !h.repository.Health().IsHealthy() {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
})
server := &http.Server{
Addr: ":8733",
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
}
l, err := net.Listen("tcp", server.Addr)
if err != nil {
return nil, fmt.Errorf("could not listen on %s: %w", server.Addr, err)
}
go func() {
if err := server.Serve(l); err != nil && !errors.Is(err, http.ErrServerClosed) {
panic(err)
}
}()
cleanup := func() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
return fmt.Errorf("could not shutdown server: %w", err)
}
return nil
}
return cleanup, nil
}