-
Notifications
You must be signed in to change notification settings - Fork 961
/
main.go
271 lines (225 loc) · 6.47 KB
/
main.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
package main
import (
"context"
"errors"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/hibiken/asynq"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/rakyll/statik/fs"
"github.com/rs/cors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/techschool/simplebank/api"
db "github.com/techschool/simplebank/db/sqlc"
_ "github.com/techschool/simplebank/doc/statik"
"github.com/techschool/simplebank/gapi"
"github.com/techschool/simplebank/mail"
"github.com/techschool/simplebank/pb"
"github.com/techschool/simplebank/util"
"github.com/techschool/simplebank/worker"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
"google.golang.org/protobuf/encoding/protojson"
)
var interruptSignals = []os.Signal{
os.Interrupt,
syscall.SIGTERM,
syscall.SIGINT,
}
func main() {
config, err := util.LoadConfig(".")
if err != nil {
log.Fatal().Err(err).Msg("cannot load config")
}
if config.Environment == "development" {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
}
ctx, stop := signal.NotifyContext(context.Background(), interruptSignals...)
defer stop()
connPool, err := pgxpool.New(ctx, config.DBSource)
if err != nil {
log.Fatal().Err(err).Msg("cannot connect to db")
}
runDBMigration(config.MigrationURL, config.DBSource)
store := db.NewStore(connPool)
redisOpt := asynq.RedisClientOpt{
Addr: config.RedisAddress,
}
taskDistributor := worker.NewRedisTaskDistributor(redisOpt)
waitGroup, ctx := errgroup.WithContext(ctx)
runTaskProcessor(ctx, waitGroup, config, redisOpt, store)
runGatewayServer(ctx, waitGroup, config, store, taskDistributor)
runGrpcServer(ctx, waitGroup, config, store, taskDistributor)
err = waitGroup.Wait()
if err != nil {
log.Fatal().Err(err).Msg("error from wait group")
}
}
func runDBMigration(migrationURL string, dbSource string) {
migration, err := migrate.New(migrationURL, dbSource)
if err != nil {
log.Fatal().Err(err).Msg("cannot create new migrate instance")
}
if err = migration.Up(); err != nil && err != migrate.ErrNoChange {
log.Fatal().Err(err).Msg("failed to run migrate up")
}
log.Info().Msg("db migrated successfully")
}
func runTaskProcessor(
ctx context.Context,
waitGroup *errgroup.Group,
config util.Config,
redisOpt asynq.RedisClientOpt,
store db.Store,
) {
mailer := mail.NewGmailSender(config.EmailSenderName, config.EmailSenderAddress, config.EmailSenderPassword)
taskProcessor := worker.NewRedisTaskProcessor(redisOpt, store, mailer)
log.Info().Msg("start task processor")
err := taskProcessor.Start()
if err != nil {
log.Fatal().Err(err).Msg("failed to start task processor")
}
waitGroup.Go(func() error {
<-ctx.Done()
log.Info().Msg("graceful shutdown task processor")
taskProcessor.Shutdown()
log.Info().Msg("task processor is stopped")
return nil
})
}
func runGrpcServer(
ctx context.Context,
waitGroup *errgroup.Group,
config util.Config,
store db.Store,
taskDistributor worker.TaskDistributor,
) {
server, err := gapi.NewServer(config, store, taskDistributor)
if err != nil {
log.Fatal().Err(err).Msg("cannot create server")
}
gprcLogger := grpc.UnaryInterceptor(gapi.GrpcLogger)
grpcServer := grpc.NewServer(gprcLogger)
pb.RegisterSimpleBankServer(grpcServer, server)
reflection.Register(grpcServer)
listener, err := net.Listen("tcp", config.GRPCServerAddress)
if err != nil {
log.Fatal().Err(err).Msg("cannot create listener")
}
waitGroup.Go(func() error {
log.Info().Msgf("start gRPC server at %s", listener.Addr().String())
err = grpcServer.Serve(listener)
if err != nil {
if errors.Is(err, grpc.ErrServerStopped) {
return nil
}
log.Error().Err(err).Msg("gRPC server failed to serve")
return err
}
return nil
})
waitGroup.Go(func() error {
<-ctx.Done()
log.Info().Msg("graceful shutdown gRPC server")
grpcServer.GracefulStop()
log.Info().Msg("gRPC server is stopped")
return nil
})
}
func runGatewayServer(
ctx context.Context,
waitGroup *errgroup.Group,
config util.Config,
store db.Store,
taskDistributor worker.TaskDistributor,
) {
server, err := gapi.NewServer(config, store, taskDistributor)
if err != nil {
log.Fatal().Err(err).Msg("cannot create server")
}
jsonOption := runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{
MarshalOptions: protojson.MarshalOptions{
UseProtoNames: true,
},
UnmarshalOptions: protojson.UnmarshalOptions{
DiscardUnknown: true,
},
})
grpcMux := runtime.NewServeMux(jsonOption)
err = pb.RegisterSimpleBankHandlerServer(ctx, grpcMux, server)
if err != nil {
log.Fatal().Err(err).Msg("cannot register handler server")
}
mux := http.NewServeMux()
mux.Handle("/", grpcMux)
statikFS, err := fs.New()
if err != nil {
log.Fatal().Err(err).Msg("cannot create statik fs")
}
swaggerHandler := http.StripPrefix("/swagger/", http.FileServer(statikFS))
mux.Handle("/swagger/", swaggerHandler)
c := cors.New(cors.Options{
AllowedOrigins: config.AllowedOrigins,
AllowedMethods: []string{
http.MethodHead,
http.MethodOptions,
http.MethodGet,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
},
AllowedHeaders: []string{
"Content-Type",
"Authorization",
},
AllowCredentials: true,
})
handler := c.Handler(gapi.HttpLogger(mux))
httpServer := &http.Server{
Handler: handler,
Addr: config.HTTPServerAddress,
}
waitGroup.Go(func() error {
log.Info().Msgf("start HTTP gateway server at %s", httpServer.Addr)
err = httpServer.ListenAndServe()
if err != nil {
if errors.Is(err, http.ErrServerClosed) {
return nil
}
log.Error().Err(err).Msg("HTTP gateway server failed to serve")
return err
}
return nil
})
waitGroup.Go(func() error {
<-ctx.Done()
log.Info().Msg("graceful shutdown HTTP gateway server")
err := httpServer.Shutdown(context.Background())
if err != nil {
log.Error().Err(err).Msg("failed to shutdown HTTP gateway server")
return err
}
log.Info().Msg("HTTP gateway server is stopped")
return nil
})
}
func runGinServer(config util.Config, store db.Store) {
server, err := api.NewServer(config, store)
if err != nil {
log.Fatal().Err(err).Msg("cannot create server")
}
err = server.Start(config.HTTPServerAddress)
if err != nil {
log.Fatal().Err(err).Msg("cannot start server")
}
}