-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
216 lines (180 loc) · 6.11 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
package main
import (
"context"
"database/sql"
"embed"
"errors"
"fmt"
"io/fs"
"log/slog"
"net/http"
"net/url"
"os"
"os/signal"
"syscall"
"time"
"github.com/MicahParks/jwkset"
"github.com/MicahParks/keyfunc/v3"
"github.com/exaring/otelpgx"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/invopop/ctxi18n"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/pressly/goose/v3"
pgxUUID "github.com/vgarvardt/pgx-google-uuid/v5"
"gitlab.com/hmajid2301/banterbus/internal/config"
"gitlab.com/hmajid2301/banterbus/internal/logging"
"gitlab.com/hmajid2301/banterbus/internal/service"
"gitlab.com/hmajid2301/banterbus/internal/service/randomizer"
"gitlab.com/hmajid2301/banterbus/internal/store/db"
"gitlab.com/hmajid2301/banterbus/internal/store/pubsub"
"gitlab.com/hmajid2301/banterbus/internal/telemetry"
transporthttp "gitlab.com/hmajid2301/banterbus/internal/transport/http"
"gitlab.com/hmajid2301/banterbus/internal/transport/websockets"
"gitlab.com/hmajid2301/banterbus/internal/views"
)
//go:embed internal/store/db/sqlc/migrations/*.sql
var migrations embed.FS
//go:embed static
var staticFiles embed.FS
func main() {
var exitCode int
err := mainLogic()
if err != nil {
logger := logging.New(slog.LevelInfo, []slog.Attr{})
logger.ErrorContext(context.Background(), "failed to start app", slog.Any("error", err))
exitCode = 1
}
defer func() { os.Exit(exitCode) }()
}
func mainLogic() error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
conf, err := config.LoadConfig(ctx)
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
hostname, err := os.Hostname()
if err != nil {
return fmt.Errorf("failed to fetch hostname: %w", err)
}
otelShutdown, err := telemetry.SetupOTelSDK(ctx, conf.App.Environment)
if err != nil {
return fmt.Errorf("failed to setup otel: %w", err)
}
defer func() {
err = errors.Join(err, otelShutdown(context.Background()))
}()
// TODO: take these values from otel? instrument via otel?
logger := logging.New(conf.App.LogLevel, []slog.Attr{
slog.String("app_name", "banterbus"),
slog.String("node", hostname),
slog.String("environment", conf.App.Environment),
})
// TODO: refactor this
pgxConfig, err := pgxpool.ParseConfig(conf.DB.URI)
if err != nil {
return fmt.Errorf("failed to parse db uri: %w", err)
}
pgxConfig.ConnConfig.Tracer = otelpgx.NewTracer()
pgxConfig.AfterConnect = func(_ context.Context, conn *pgx.Conn) error {
pgxUUID.Register(conn.TypeMap())
return nil
}
pool, err := pgxpool.NewWithConfig(ctx, pgxConfig)
if err != nil {
return fmt.Errorf("failed to setup database: %w", err)
}
defer pool.Close()
logger.InfoContext(ctx, "applying migrations")
err = runDBMigrations(pool)
if err != nil {
return fmt.Errorf("failed to run migrations: %w", err)
}
str, err := db.NewDB(pool)
if err != nil {
return fmt.Errorf("failed to setup store: %w", err)
}
err = ctxi18n.LoadWithDefault(views.Locales, conf.App.DefaultLocale)
if err != nil {
return fmt.Errorf("error loading locales: %w", err)
}
userRandomizer := randomizer.NewUserRandomizer()
lobbyService := service.NewLobbyService(str, userRandomizer, conf.App.DefaultLocale.String())
playerService := service.NewPlayerService(str, userRandomizer)
roundService := service.NewRoundService(str, userRandomizer, conf.App.DefaultLocale.String())
questionService := service.NewQuestionService(str, userRandomizer, conf.App.DefaultLocale.String())
fsys, err := fs.Sub(staticFiles, "static")
if err != nil {
return fmt.Errorf("failed to create embed file system: %w", err)
}
redisClient, err := pubsub.NewRedisClient(conf.Redis.Address)
if err != nil {
return fmt.Errorf("failed to create redis client: %w", err)
}
rules, err := views.RuleMarkdown()
if err != nil {
return fmt.Errorf("failed to convert rules MD to HTML: %w", err)
}
subscriber := websockets.NewSubscriber(lobbyService, playerService, roundService, logger, redisClient, conf, rules)
u, err := url.Parse(conf.JWT.JWKSURL)
if err != nil {
return fmt.Errorf("failed to parse jwks URL: %w", err)
}
// TODO: should we stop startup if this is failing?
storage, err := jwkset.NewStorageFromHTTP(u, jwkset.HTTPClientStorageOptions{Ctx: ctx})
if err != nil {
return fmt.Errorf("failed to jwkset storage: %w", err)
}
k, err := keyfunc.New(keyfunc.Options{
Storage: storage,
})
if err != nil {
return fmt.Errorf("failed to create keyfunc: %w", err)
}
serverConfig := transporthttp.ServerConfig{
Host: conf.Server.Host,
Port: conf.Server.Port,
DefaultLocale: conf.App.DefaultLocale,
Environment: conf.App.Environment,
}
server := transporthttp.NewServer(subscriber, logger, http.FS(fsys), k.Keyfunc, questionService, serverConfig)
timeoutSeconds := 15
go terminateHandler(ctx, logger, server, timeoutSeconds)
err = server.Serve(ctx)
if err != nil {
return fmt.Errorf("failed to start server: %w", err)
}
return nil
}
// terminateHandler waits for SIGINT or SIGTERM signals and does a graceful shutdown of the HTTP server
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 5 seconds.
// kill (no param) default send syscall.SIGTERM
// kill -2 is syscall.SIGINT
// kill -9 is syscall.SIGKILL but can't be catch, so don't need add it
func terminateHandler(ctx context.Context, logger *slog.Logger, srv *transporthttp.Server, timeout int) {
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
logger.InfoContext(ctx, "shutting down server")
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
logger.ErrorContext(ctx, "unexpected error while shutting down server", slog.Any("error", err))
}
}
func runDBMigrations(pool *pgxpool.Pool) error {
goose.SetBaseFS(migrations)
goose.WithLogger(goose.NopLogger())
if err := goose.SetDialect("postgres"); err != nil {
return err
}
cp := pool.Config().ConnConfig.ConnString()
db, err := sql.Open("pgx/v5", cp)
if err != nil {
return err
}
err = goose.Up(db, "internal/store/db/sqlc/migrations")
return err
}