aboutsummaryrefslogtreecommitdiffhomepage
path: root/backend/main.go
blob: 3ea44932cf086fc6cd93a8ffe4780f05721fdc5f (plain)
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
package main

import (
	"context"
	"fmt"
	"log/slog"
	"net/http"
	"os"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	oapimiddleware "github.com/oapi-codegen/echo-middleware"
	"golang.org/x/time/rate"

	"albatross-2026-backend/admin"
	"albatross-2026-backend/api"
	"albatross-2026-backend/auth"
	"albatross-2026-backend/config"
	"albatross-2026-backend/db"
	"albatross-2026-backend/game"
	"albatross-2026-backend/ratelimit"
	"albatross-2026-backend/taskqueue"
)

func connectDB(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
	pool, err := pgxpool.New(ctx, dsn)
	if err != nil {
		return nil, err
	}

	if err := pool.Ping(ctx); err != nil {
		return nil, err
	}

	return pool, nil
}

func main() {
	var err error
	conf, err := config.NewConfigFromEnv()
	if err != nil {
		slog.Error("failed to load env", "error", err)
		os.Exit(1)
	}

	openAPISpec, err := api.GetSwaggerWithPrefix(conf.BasePath + "api")
	if err != nil {
		slog.Error("failed to load OpenAPI spec", "error", err)
		os.Exit(1)
	}

	ctx := context.Background()

	dbDSN := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", conf.DBHost, conf.DBPort, conf.DBUser, conf.DBPassword, conf.DBName)
	connPool, err := connectDB(ctx, dbDSN)
	if err != nil {
		slog.Error("failed to connect to db", "error", err)
		os.Exit(1)
	}
	defer connPool.Close()

	queries := db.New(connPool)
	txm := db.NewTxManager(connPool, queries)
	authenticator := auth.NewAuthenticator(queries, txm)

	e := echo.New()
	e.Renderer = admin.NewRenderer()

	e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
		LogStatus:   true,
		LogURI:      true,
		LogMethod:   true,
		LogLatency:  true,
		LogError:    true,
		HandleError: true,
		LogValuesFunc: func(_ echo.Context, v middleware.RequestLoggerValues) error {
			attrs := []slog.Attr{
				slog.String("method", v.Method),
				slog.String("uri", v.URI),
				slog.Int("status", v.Status),
				slog.Duration("latency", v.Latency),
			}
			if v.Error != nil {
				attrs = append(attrs, slog.String("error", v.Error.Error()))
			}
			slog.LogAttrs(context.Background(), slog.LevelInfo, "request", attrs...)
			return nil
		},
	}))
	e.Use(middleware.Recover())

	taskQueue := taskqueue.NewQueue("task-db:6379")
	workerServer := taskqueue.NewWorkerServer("task-db:6379")

	gameHub := game.NewGameHub(queries, txm, taskQueue, workerServer)

	loginRL := ratelimit.NewIPRateLimiter(rate.Every(time.Minute/5), 5)

	apiGroup := e.Group(conf.BasePath + "api")
	apiGroup.Use(ratelimit.LoginRateLimitMiddleware(loginRL))
	apiGroup.Use(api.SessionCookieMiddleware(queries))
	apiGroup.Use(oapimiddleware.OapiRequestValidator(openAPISpec))
	apiHandler := api.NewHandler(queries, txm, gameHub, authenticator, conf)
	api.RegisterHandlers(apiGroup, api.NewStrictHandler(apiHandler, nil))

	adminHandler := admin.NewHandler(queries, txm, gameHub, conf)
	adminGroup := e.Group(conf.BasePath + "admin")
	adminGroup.Use(api.SessionCookieMiddleware(queries))
	adminHandler.RegisterHandlers(adminGroup)

	if conf.IsLocal {
		filesGroup := e.Group(conf.BasePath + "files")
		filesGroup.Use(middleware.StaticWithConfig(middleware.StaticConfig{
			Root:       "/",
			Filesystem: http.Dir("/data/files"),
			IgnoreBase: true,
		}))

		e.GET(conf.BasePath+"*", func(c echo.Context) error {
			return c.Redirect(http.StatusPermanentRedirect, "http://localhost:5173"+c.Request().URL.Path)
		})
		e.POST(conf.BasePath+"*", func(c echo.Context) error {
			return c.Redirect(http.StatusPermanentRedirect, "http://localhost:5173"+c.Request().URL.Path)
		})

		// Allow access from dev server.
		e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
			AllowOrigins:     []string{"http://localhost:5173"},
			AllowCredentials: true,
		}))
	}

	sessionCleanupCtx, cancelSessionCleanup := context.WithCancel(context.Background())
	defer cancelSessionCleanup()
	go func() {
		ticker := time.NewTicker(time.Hour)
		defer ticker.Stop()
		for {
			select {
			case <-sessionCleanupCtx.Done():
				return
			case <-ticker.C:
				if err := queries.DeleteExpiredSessions(sessionCleanupCtx); err != nil {
					slog.Error("failed to delete expired sessions", "error", err)
				}
			}
		}
	}()

	go gameHub.Run()

	if err := e.Start(":80"); err != http.ErrServerClosed {
		slog.Error("failed to start server", "error", err)
		os.Exit(1)
	}
}