-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.server.go
204 lines (178 loc) · 5.96 KB
/
app.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
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"runtime"
"syscall"
"github.com/julienschmidt/httprouter"
"github.com/redis/go-redis/v9"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
)
type AppProvider interface {
Run() error
Serve() func() error
Stop(context.Context, context.Context) func() error
}
type App struct {
logger *zap.Logger
config *Config
server *http.Server
redisClient *redis.Client
cleanups []func() error
queueConsumers []func(context.Context) error
}
// NewApp provides an instance of App.
func NewApp() (AppProvider, error) {
var app *App
config, err := LoadAndInitConfigs(GitCommit, GitTag, BuildTime)
if err != nil {
return nil, fmt.Errorf("failed to setup app configuration: %s", err)
}
// ensure the logs folder exists and Setup the logging module.
err = os.MkdirAll(config.LogFolder, 0o700)
if err != nil {
return nil, fmt.Errorf("logging: failed to create folder: %v", err)
}
clock := NewClock(config.IsProduction)
rswriter := NewRSyncWriter(config, clock)
logger, logsFlusher := SetupLogging(config, rswriter, NewTickClock(clock))
// Setup the connection to redis and boltDB servers.
redisClient, err := NewRedisClient(config)
if err != nil {
return app, fmt.Errorf("failed to connect to redis server: %s", err)
}
boltDBClient, err := GetBoltDBClient(config)
if err != nil {
return app, fmt.Errorf("failed to connect to boltDB server: %s", err)
}
boltBookStorage := NewBoltBookStorage(logger, &config.BoltDB, boltDBClient)
// Setup the repository and api services and routing.
redisBookStorage := NewRedisBookStorage(logger, redisClient)
redisQueue := NewRedisQueue(redisClient)
boltDBConsumer := NewBoltDBConsumer(logger, redisQueue, boltBookStorage)
bookService := NewBookService(logger, config, clock, redisBookStorage, boltBookStorage, redisQueue)
stats := NewStatistics(config.GitTag, config.GitCommit, runtime.Version(), runtime.GOOS+"/"+runtime.GOARCH, IsAppRunningInDocker(), clock.Now())
apiService := NewAPIHandler(logger, config, stats, clock, NewIDsHandler(), bookService)
// Build the map of middlewares stacks.
middlewaresPublic, middlewaresOps := apiService.MiddlewaresStacks()
// Configure the endpoints with their handlers and middlewares.
router := apiService.SetupRoutes(httprouter.New(),
&MiddlewareMap{
public: middlewaresPublic.Chain,
ops: middlewaresOps.Chain,
},
)
// Build the api server definition.
srv := &http.Server{
Addr: fmt.Sprintf("%s:%s", config.Server.Host, config.Server.Port),
Handler: router,
ReadTimeout: config.Server.ReadTimeout,
WriteTimeout: config.Server.WriteTimeout,
MaxHeaderBytes: 1 << 20, // Max headers size : 1MB
ConnContext: SaveConnInContext, // add underlying connection into the request context
}
boltDBConsume := func(ctx context.Context) error {
return boltDBConsumer.Consume(ctx, CreateQueue, UpdateQueue, DeleteQueue)
}
return &App{
logger: logger,
config: config,
server: srv,
redisClient: redisClient,
cleanups: []func() error{
logsFlusher,
rswriter.Close,
},
queueConsumers: []func(ctx context.Context) error{boltDBConsume},
}, nil
}
// Run starts the api web server and a goroutine which is responsible to stop it.
func (app *App) Run() error {
nCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
g, gCtx := errgroup.WithContext(nCtx)
g.Go(app.ConsumeQueues(gCtx, g))
g.Go(app.Serve())
g.Go(app.Stop(nCtx, gCtx))
err := g.Wait()
app.logger.Info("api server stopped",
zap.String("app.host", app.config.Server.Host),
zap.String("app.port", app.config.Server.Port),
zap.Error(err),
)
errs := app.Clean()
return errors.Join(err, errs)
}
// Clean calls all registered cleanups functions and returned aggregated errors.
func (app *App) Clean() error {
var errs error
for _, f := range app.cleanups {
ferr := f()
errs = errors.Join(errs, ferr)
}
return errs
}
// Serve starts the api web server. It returned error
// will be caught by the errorgroup.
func (app *App) Serve() func() error {
return func() error {
app.logger.Info("api server starting",
zap.String("app.host", app.config.Server.Host),
zap.String("app.port", app.config.Server.Port),
)
err := app.server.ListenAndServe()
if err == http.ErrServerClosed {
err = nil
}
return err
}
}
// Stop listens for the group context and triggers the server graceful shutdown.
// It states the reason of its call. We proceed with a brutal shutdown if the
// the graceful did not complete successfully. We explicitly return `nil` to
// allow the errorgroup catches only the `Serve` method result.
func (app *App) Stop(nCtx, gCtx context.Context) func() error {
return func() error {
<-gCtx.Done()
if nCtx.Err() != nil {
app.logger.Info("api server stopping. reason: requested to stop")
} else {
app.logger.Info("api server stopping. reason: errored at running")
}
sCtx, cancel := context.WithTimeout(context.Background(), app.config.Server.ShutdownTimeout)
defer cancel()
err := app.server.Shutdown(sCtx)
switch err {
case nil, http.ErrServerClosed:
app.logger.Info("api server graceful shutdown succeeded")
case context.DeadlineExceeded:
app.logger.Info("api server graceful shutdown timed out")
default:
app.logger.Info("api server graceful shutdown failed", zap.Error(err))
}
if err != nil && err != http.ErrServerClosed {
app.logger.Info("api server going to force shutdown", zap.Error(app.server.Close()))
}
if err := app.redisClient.Close(); err != nil {
app.logger.Info("error closing redis client", zap.Error(err))
}
return nil
}
}
// ConsumeQueues runs all queue consumers into separate controlled goroutines.
func (app *App) ConsumeQueues(gCtx context.Context, g *errgroup.Group) func() error {
return func() error {
for _, consume := range app.queueConsumers {
f := func() error {
return consume(gCtx)
}
g.Go(f)
}
return nil
}
}