-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
431 lines (358 loc) · 10.6 KB
/
server.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/go-logr/logr"
"github.com/jmoiron/sqlx"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
const (
routeVarTableOrView = "tableOrView"
)
type ServerOptions struct {
Logger logr.Logger
Addr string
AuthOptions ServerAuthOptions
SecurityOptions ServerSecurityOptions
Queryer sqlx.QueryerContext
Execer sqlx.ExecerContext
}
func (opts *ServerOptions) bindCLIFlags(fs *pflag.FlagSet) {
fs.StringVar(&opts.Addr, "http-addr", ":8080", "server listen address")
opts.AuthOptions.bindCLIFlags(fs)
opts.SecurityOptions.bindCLIFlags(fs)
}
func (opts *ServerOptions) defaults() error {
if err := opts.AuthOptions.defaults(); err != nil {
return err
}
if err := opts.SecurityOptions.defaults(); err != nil {
return err
}
if opts.Logger.GetSink() == nil {
opts.Logger = logr.Discard()
}
if opts.Addr == "" {
opts.Addr = ":8080"
}
if opts.Queryer == nil {
return fmt.Errorf(".Queryer is required")
}
if opts.Execer == nil {
return fmt.Errorf(".Execer is required")
}
return nil
}
type dbServer struct {
logger logr.Logger
server *http.Server
queryer sqlx.QueryerContext
execer sqlx.ExecerContext
}
func NewServer(opts *ServerOptions) (*dbServer, error) {
if err := opts.defaults(); err != nil {
return nil, err
}
rv := &dbServer{
logger: opts.Logger.WithName("db-server"),
server: &http.Server{
Addr: opts.Addr,
// TODO: make it configurable
ReadHeaderTimeout: 5 * time.Second,
},
queryer: opts.Queryer,
execer: opts.Execer,
}
serverMux := chi.NewRouter()
// TODO: allow specifying cors config from cli / table
serverMux.Use(
middleware.RequestID,
middleware.RealIP,
serverLogger(rv.logger),
cors.AllowAll().Handler,
)
{
serverMux.
With(
opts.AuthOptions.createAuthMiddleware(func(w http.ResponseWriter, err error) {
metricsAuthFailedRequestsTotal.Inc()
rv.responseError(w, err)
}),
opts.SecurityOptions.createTableOrViewAccessCheckMiddleware(func(w http.ResponseWriter, err error) {
metricsAccessCheckFailedRequestsTotal.Inc()
rv.responseError(w, err)
}),
).
Group(func(r chi.Router) {
routePattern := fmt.Sprintf("/{%s:[^/]+}", routeVarTableOrView)
r.With(recordRequestMetrics("queryTableOrView")).Get(routePattern, rv.handleQueryTableOrView)
r.With(recordRequestMetrics("insertTable")).Post(routePattern, rv.handleInsertTable)
r.With(recordRequestMetrics("updateTable")).Patch(routePattern, rv.handleUpdateTable)
r.With(recordRequestMetrics("updateSingleEntity")).Put(routePattern, rv.handleUpdateSingleEntity)
r.With(recordRequestMetrics("deleteTable")).Delete(routePattern, rv.handleDeleteTable)
})
}
rv.server.Handler = serverMux
return rv, nil
}
func (server *dbServer) Start(done <-chan struct{}) {
go server.server.ListenAndServe()
server.logger.Info("server started", "addr", server.server.Addr)
<-done
server.logger.Info("shutting down server")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
server.server.Shutdown(shutdownCtx)
}
func (server *dbServer) responseHeader(w http.ResponseWriter, statusCode int) {
w.Header().Set("Server", ServerVersion)
w.WriteHeader(statusCode)
}
func (server *dbServer) responseError(w http.ResponseWriter, err error) {
var serverError *ServerError
switch {
case errors.As(err, &serverError):
server.responseData(w, serverError, serverError.StatusCode)
default:
resp := &ServerError{Message: err.Error()}
server.responseData(w, resp, http.StatusInternalServerError)
}
}
func (server *dbServer) responseData(w http.ResponseWriter, data interface{}, statusCode int) {
server.responseHeader(w, statusCode)
enc := json.NewEncoder(w)
if encodeErr := enc.Encode(data); encodeErr != nil {
server.logger.Error(encodeErr, "failed to write response")
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func (server *dbServer) responseEmptyBody(w http.ResponseWriter, statusCode int) {
server.responseHeader(w, statusCode)
}
func (server *dbServer) handleQueryTableOrView(
w http.ResponseWriter,
req *http.Request,
) {
target := chi.URLParam(req, routeVarTableOrView)
logger := server.logger.WithValues("target", target, "route", "handleQueryTableOrView")
qc := NewQueryCompilerFromRequest(req)
selectStmt, err := qc.CompileAsSelect(target)
if err != nil {
logger.Error(err, "parse select query")
server.responseError(w, err)
return
}
logger.V(8).Info(selectStmt.Query)
rows, err := server.queryer.QueryxContext(req.Context(), selectStmt.Query, selectStmt.Values...)
if err != nil {
logger.Error(err, "query values")
server.responseError(w, err)
return
}
defer rows.Close()
// make sure return list instead of null for empty list
// FIXME: reflect column type and scan typed value instead of using `interface{}`
rv := make([]map[string]interface{}, 0)
rows.ColumnTypes()
for rows.Next() {
p := make(map[string]interface{})
if err := rows.MapScan(p); err != nil {
server.responseError(w, err)
return
}
rv = append(rv, p)
}
responseStatusCode := http.StatusOK
w.Header().Set("Content-Type", "application/json") // TODO: horner request config
preference, err := ParsePreferenceFromRequest(req)
if err != nil {
logger.Error(err, "parse preference")
server.responseError(w, err)
return
}
var countTotal string
switch preference.Count {
case countNone:
countTotal = "*"
case countExact:
responseStatusCode = http.StatusPartialContent
countStmt, err := qc.CompileAsExactCount(target)
if err != nil {
logger.Error(err, "parse count query")
server.responseError(w, err)
return
}
logger.V(8).Info(countStmt.Query)
var count int64
if err := server.queryer.QueryRowxContext(
req.Context(),
countStmt.Query, countStmt.Values...,
).Scan(&count); err != nil {
logger.Error(err, "count values")
server.responseError(w, err)
return
}
countTotal = fmt.Sprint(count)
}
if v := qc.CompileContentRangeHeader(countTotal); v != "" {
w.Header().Set("Range-Unit", "items")
w.Header().Set("Content-Range", v)
}
server.responseData(w, rv, responseStatusCode)
}
func (server *dbServer) handleInsertTable(
w http.ResponseWriter,
req *http.Request,
) {
target := chi.URLParam(req, routeVarTableOrView)
logger := server.logger.WithValues("target", target, "route", "handleInsertTable")
qc := NewQueryCompilerFromRequest(req)
insertStmt, err := qc.CompileAsInsert(target)
if err != nil {
logger.Error(err, "parse insert query")
server.responseError(w, err)
return
}
logger.V(8).Info(insertStmt.Query)
_, err = server.execer.ExecContext(req.Context(), insertStmt.Query, insertStmt.Values...)
if err != nil {
server.responseError(w, err)
return
}
// TODO: implement support for retrieving object by inserted id
server.responseEmptyBody(w, http.StatusCreated)
}
func (server *dbServer) handleUpdateTable(
w http.ResponseWriter,
req *http.Request,
) {
target := chi.URLParam(req, routeVarTableOrView)
logger := server.logger.WithValues("target", target, "route", "handleUpdateTable")
qc := NewQueryCompilerFromRequest(req)
updateStmt, err := qc.CompileAsUpdate(target)
if err != nil {
logger.Error(err, "parse update query")
server.responseError(w, err)
return
}
logger.V(8).Info(updateStmt.Query)
_, err = server.execer.ExecContext(req.Context(), updateStmt.Query, updateStmt.Values...)
if err != nil {
server.responseError(w, err)
return
}
server.responseEmptyBody(w, http.StatusAccepted)
}
func (server *dbServer) handleUpdateSingleEntity(
w http.ResponseWriter,
req *http.Request,
) {
target := chi.URLParam(req, routeVarTableOrView)
logger := server.logger.WithValues("target", target, "route", "handleUpdateSingleEntity")
qc := NewQueryCompilerFromRequest(req)
updateStmt, err := qc.CompileAsUpdateSingleEntry(target)
if err != nil {
logger.Error(err, "parse update single entry query")
server.responseError(w, err)
return
}
logger.V(8).Info(updateStmt.Query)
_, err = server.execer.ExecContext(req.Context(), updateStmt.Query, updateStmt.Values...)
if err != nil {
server.responseError(w, err)
return
}
}
func (server *dbServer) handleDeleteTable(
w http.ResponseWriter,
req *http.Request,
) {
target := chi.URLParam(req, routeVarTableOrView)
logger := server.logger.WithValues("target", target, "route", "handleDeleteTable")
qc := NewQueryCompilerFromRequest(req)
updateStmt, err := qc.CompileAsDelete(target)
if err != nil {
logger.Error(err, "parse delete query")
server.responseError(w, err)
return
}
logger.V(8).Info(updateStmt.Query)
_, err = server.execer.ExecContext(req.Context(), updateStmt.Query, updateStmt.Values...)
if err != nil {
server.responseError(w, err)
return
}
server.responseEmptyBody(w, http.StatusAccepted)
}
func createServeCmd() *cobra.Command {
serverOpts := new(ServerOptions)
metricsServerOpts := new(MetricsServerOptions)
pprofServerOpts := new(PprofServerOptions)
cmd := &cobra.Command{
Use: "serve",
Short: "Start database server",
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
logger, err := createLogger(cmd)
if err != nil {
setupLogger.Error(err, "failed to create logger")
return err
}
db, err := openDB(cmd)
if err != nil {
setupLogger.Error(err, "failed to open db")
return err
}
defer db.Close()
serverOpts.Logger = logger
serverOpts.Queryer = db
serverOpts.Execer = db
server, err := NewServer(serverOpts)
if err != nil {
setupLogger.Error(err, "failed to create server")
return err
}
metricsServerOpts.Logger = logger
metricsServerOpts.Queryer = db
metricsServer, err := NewMetricsServer(*metricsServerOpts)
if err != nil {
setupLogger.Error(err, "failed to create metrics server")
return err
}
pprofServerOpts.Logger = logger
pprofServer, err := NewPprofServer(*pprofServerOpts)
if err != nil {
setupLogger.Error(err, "failed to create pprof server")
return err
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
done := ctx.Done()
go metricsServer.Start(done)
go pprofServer.Start(done)
go server.Start(done)
<-sigs
return nil
},
}
serverOpts.bindCLIFlags(cmd.Flags())
metricsServerOpts.bindCLIFlags(cmd.Flags())
pprofServerOpts.bindCLIFlags(cmd.Flags())
bindDBDSNFlag(cmd.Flags())
return cmd
}