-
-
Notifications
You must be signed in to change notification settings - Fork 171
/
serv.go
265 lines (216 loc) · 4.8 KB
/
serv.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package serv
import (
"context"
"embed"
"fmt"
"io/fs"
"net/http"
"os"
"os/signal"
"path"
"strings"
"time"
"github.com/NYTimes/gziphandler"
"github.com/dosco/graphjin/serv/internal/auth"
"go.opencensus.io/plugin/ochttp"
)
const (
serverName = "GraphJin"
)
var (
// These variables are set using -ldflags
version string
commit string
date string
)
var (
//go:embed web/build
webBuild embed.FS
apiRoute string = "/api/v1/graphql"
)
func initWatcher(s *Service) {
cpath := s.conf.Serv.ConfigPath
var d dir
if cpath == "" || cpath == "./" {
d = watchDir("./config", reExec(s))
} else {
d = watchDir(cpath, reExec(s))
}
go func() {
err := do(s, s.log.Infof, d)
if err != nil {
s.log.Fatalf("Error in config file wacher: %s", err)
}
}()
}
func isHealthEndpoint(r *http.Request) bool {
healthEndPointPaths := []string{"/health", "/metrics"}
for _, healthEndPointPath := range healthEndPointPaths {
if r.URL.Path == healthEndPointPath {
return true
}
}
return false
}
func startHTTP(s *Service) {
var appName string
defaultHP := "0.0.0.0:8080"
env := os.Getenv("GO_ENV")
if s.conf != nil {
appName = s.conf.AppName
hp := strings.SplitN(s.conf.HostPort, ":", 2)
if len(hp) == 2 {
if s.conf.Host != "" {
hp[0] = s.conf.Host
}
if s.conf.Port != "" {
hp[1] = s.conf.Port
}
s.conf.hostPort = fmt.Sprintf("%s:%s", hp[0], hp[1])
}
}
if s.conf.hostPort == "" {
s.conf.hostPort = defaultHP
}
routes, err := routeHandler(s, http.NewServeMux())
if err != nil {
s.log.Fatalf("Error setting up API routes: %s", err)
}
srv := &http.Server{
Addr: s.conf.hostPort,
Handler: routes,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
if s.conf.telemetryEnabled() {
if s.conf.Serv.Telemetry.Tracing.ExcludeHealthCheck {
srv.Handler = &ochttp.Handler{
Handler: routes,
IsHealthEndpoint: isHealthEndpoint,
}
} else {
srv.Handler = &ochttp.Handler{Handler: routes}
}
}
idleConnsClosed := make(chan struct{})
go func() {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)
<-sigint
if err := srv.Shutdown(context.Background()); err != nil {
s.log.Warn("Shutdown signal received")
}
close(idleConnsClosed)
}()
srv.RegisterOnShutdown(func() {
if s.conf.closeFn != nil {
s.conf.closeFn()
}
if s.db != nil {
s.db.Close()
}
s.log.Info("Shutdown complete")
})
s.log.Infof("GraphJin started, version: %s, host-port: %s, app-name: %s, env: %s\n",
version, s.conf.hostPort, appName, env)
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
s.log.Fatal("Server stopped")
}
<-idleConnsClosed
}
func routeHandler(s *Service, mux *http.ServeMux) (http.Handler, error) {
var err error
if s.conf == nil {
return mux, nil
}
if s.conf.APIPath != "" {
apiRoute = path.Join("/", s.conf.APIPath, "/v1/graphql")
}
// Main GraphQL API handler
apiHandler := apiV1Handler(s)
// API rate limiter
if s.conf.rateLimiterEnable() {
apiHandler = rateLimiter(s, apiHandler)
}
routes := map[string]http.Handler{
"/health": http.HandlerFunc(health(s)),
apiRoute: apiHandler,
}
if err := setActionRoutes(s, routes); err != nil {
return nil, err
}
if s.conf.WebUI {
webRoot, err := fs.Sub(webBuild, "web/build")
if err != nil {
return nil, err
}
routes["/"] = http.FileServer(http.FS(webRoot))
}
if s.conf.HTTPGZip {
gz := gziphandler.MustNewGzipLevelHandler(6)
for k, v := range routes {
routes[k] = gz(v)
}
}
for k, v := range routes {
mux.Handle(k, v)
}
if s.conf.telemetryEnabled() {
s.conf.closeFn, err = enableObservability(s, mux)
if err != nil {
return nil, err
}
}
return setServerHeader(mux), nil
}
func setServerHeader(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Server", serverName)
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func setActionRoutes(s *Service, routes map[string]http.Handler) error {
var err error
for _, a := range s.conf.Actions {
var fn http.Handler
fn, err = newAction(s, &a)
if err != nil {
break
}
p := fmt.Sprintf("/api/v1/actions/%s", strings.ToLower(a.Name))
if ac := findAuth(s, a.AuthName); ac != nil {
routes[p], err = auth.WithAuth(fn, ac)
} else {
routes[p] = fn
}
if s.conf.telemetryEnabled() {
routes[p] = ochttp.WithRouteTag(routes[p], p)
}
if err != nil {
return err
}
}
return nil
}
func findAuth(s *Service, name string) *auth.Auth {
for _, a := range s.conf.Auths {
if strings.EqualFold(a.Name, name) {
return &a
}
}
return nil
}
type BuildInfo struct {
Version string
Commit string
Date string
}
func GetBuildInfo() BuildInfo {
return BuildInfo{
Version: version,
Commit: commit,
Date: date,
}
}