all repos

onasty @ f01c95c

a one-time notes service

onasty/cmd/api/main.go(view raw)

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
package main

import (
	"context"
	"errors"
	"fmt"
	"log/slog"
	"net/http"
	"os"
	"os/signal"

	"github.com/gin-gonic/gin"
	"github.com/nats-io/nats.go"
	"github.com/olexsmir/onasty/internal/config"
	"github.com/olexsmir/onasty/internal/events/mailermq"
	"github.com/olexsmir/onasty/internal/hasher"
	"github.com/olexsmir/onasty/internal/jwtutil"
	"github.com/olexsmir/onasty/internal/logger"
	"github.com/olexsmir/onasty/internal/metrics"
	"github.com/olexsmir/onasty/internal/oauth"
	"github.com/olexsmir/onasty/internal/service/notesrv"
	"github.com/olexsmir/onasty/internal/service/usersrv"
	"github.com/olexsmir/onasty/internal/store/psql/noterepo"
	"github.com/olexsmir/onasty/internal/store/psql/passwordtokrepo"
	"github.com/olexsmir/onasty/internal/store/psql/sessionrepo"
	"github.com/olexsmir/onasty/internal/store/psql/userepo"
	"github.com/olexsmir/onasty/internal/store/psql/vertokrepo"
	"github.com/olexsmir/onasty/internal/store/psqlutil"
	"github.com/olexsmir/onasty/internal/store/rdb"
	"github.com/olexsmir/onasty/internal/store/rdb/notecache"
	"github.com/olexsmir/onasty/internal/store/rdb/usercache"
	httptransport "github.com/olexsmir/onasty/internal/transport/http"
	"github.com/olexsmir/onasty/internal/transport/http/httpserver"
	"github.com/olexsmir/onasty/internal/transport/http/ratelimit"
)

func main() {
	if err := run(context.Background()); err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
		os.Exit(1)
	}
}

//nolint:err113,funlen
func run(ctx context.Context) error {
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	cfg := config.NewConfig()

	// logger
	if err := logger.SetDefault(cfg.LogLevel, cfg.LogFormat, cfg.LogShowLine); err != nil {
		return err
	}

	// semi dev mode
	if !cfg.AppEnv.IsDevMode() {
		gin.SetMode(gin.ReleaseMode)
	}

	// app deps
	nc, err := nats.Connect(cfg.NatsURL)
	if err != nil {
		return err
	}

	psqlDB, err := psqlutil.Connect(ctx, cfg.PostgresDSN)
	if err != nil {
		return err
	}

	redisDB, err := rdb.Connect(ctx, cfg.RedisAddr, cfg.RedisPassword, cfg.RedisDB)
	if err != nil {
		return err
	}

	userPasswordHasher := hasher.NewSHA256Hasher(cfg.PasswordSalt)
	notePasswordHasher := hasher.NewSHA256Hasher(cfg.NotePasswordSalt)
	jwtTokenizer := jwtutil.NewJWTUtil(cfg.JwtSigningKey, cfg.JwtAccessTokenTTL)

	googleOauth := oauth.NewGoogleProvider(
		cfg.GoogleClientID,
		cfg.GoogleSecret,
		cfg.GoogleRedirectURL,
	)
	githubOauth := oauth.NewGithubProvider(
		cfg.GitHubClientID,
		cfg.GitHubSecret,
		cfg.GitHubRedirectURL,
	)

	mailermq := mailermq.New(nc)

	sessionrepo := sessionrepo.New(psqlDB)
	vertokrepo := vertokrepo.New(psqlDB)
	pwdtokrepo := passwordtokrepo.NewPasswordResetTokenRepo(psqlDB)

	userepo := userepo.New(psqlDB)
	usercache := usercache.New(redisDB, cfg.CacheUsersTTL)
	usersrv := usersrv.New(
		userepo,
		sessionrepo,
		vertokrepo,
		pwdtokrepo,
		userPasswordHasher,
		jwtTokenizer,
		mailermq,
		usercache,
		googleOauth,
		githubOauth,
		cfg.JwtRefreshTokenTTL,
		cfg.VerificationTokenTTL,
		cfg.ResetPasswordTokenTTL,
	)

	notecache := notecache.New(redisDB, cfg.CacheNoteTTL)
	noterepo := noterepo.New(psqlDB)
	notesrv := notesrv.New(noterepo, notePasswordHasher, notecache)

	rateLimiterConfig := ratelimit.Config{
		RPS:   cfg.RateLimiterRPS,
		TTL:   cfg.RateLimiterTTL,
		Burst: cfg.RateLimiterBurst,
	}

	handler := httptransport.NewTransport(
		usersrv,
		notesrv,
		cfg.AppEnv,
		cfg.AppURL,
		cfg.CORSAllowedOrigins,
		cfg.CORSMaxAge,
		rateLimiterConfig,
	)

	// http server
	srv := httpserver.NewServer(handler.Handler(), httpserver.Config{
		Port:            cfg.HTTPPort,
		ReadTimeout:     cfg.HTTPReadTimeout,
		WriteTimeout:    cfg.HTTPWriteTimeout,
		MaxHeaderSizeMb: cfg.HTTPHeaderMaxSizeMb,
	})
	go func() {
		slog.Info("starting http server", "port", cfg.HTTPPort)
		if err := srv.Start(); !errors.Is(err, http.ErrServerClosed) {
			slog.Error("failed to start http server", "error", err)
		}
	}()

	// metrics
	if cfg.MetricsEnabled {
		mSrv := httpserver.NewDefaultServer(metrics.Handler(), cfg.MetricsPort)
		go func() {
			slog.Info("starting metrics server", "port", cfg.MetricsPort)
			if err := mSrv.Start(); !errors.Is(err, http.ErrServerClosed) {
				slog.Error("failed to start metrics server", "error", err)
			}
		}()
	}

	// graceful shutdown
	quitCh := make(chan os.Signal, 1)
	signal.Notify(quitCh, os.Interrupt)
	<-quitCh

	if err := srv.Stop(ctx); err != nil {
		return errors.Join(errors.New("failed to stop http server"), err)
	}

	if err := psqlDB.Close(); err != nil {
		return errors.Join(errors.New("failed to close postgres connection"), err)
	}

	if err := redisDB.Close(); err != nil {
		return errors.Join(errors.New("failed to close redis connection"), err)
	}

	return nil
}