forked from mtusi2026/mtusi2026lab2
Проверка и завершение требований уровней «3» и «4»
This commit is contained in:
@@ -63,12 +63,13 @@ func run() error {
|
||||
middleware.NewAuthMiddleware(authSvc),
|
||||
middleware.RequestIDMiddleware(),
|
||||
middleware.LoggingMiddleware(),
|
||||
middleware.RequestTimeout(cfg.Postgres.QueryTimeout),
|
||||
)
|
||||
server := http.New(cfg, httpRouter)
|
||||
requestValidator := validator.NewValidatorImpl()
|
||||
registerRoutes(
|
||||
http.NewAuthHandler(httpRouter, authSvc),
|
||||
http.NewHealthHandler(httpRouter, server),
|
||||
http.NewHealthHandler(httpRouter, server, pgx),
|
||||
http.NewChatHandler(httpRouter, provider, requestValidator, chatSvc),
|
||||
http.NewUserHandler(httpRouter, provider, requestValidator, userSvc),
|
||||
)
|
||||
@@ -99,6 +100,7 @@ func run() error {
|
||||
if err = rx.Close(); err != nil {
|
||||
return fmt.Errorf("close redis: %w", err)
|
||||
}
|
||||
pgx.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
@@ -9,15 +11,19 @@ import (
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
)
|
||||
|
||||
type databasePinger interface{ Ping(context.Context) error }
|
||||
|
||||
type HealthHandler struct {
|
||||
router router.Router
|
||||
server Server
|
||||
router router.Router
|
||||
server Server
|
||||
database databasePinger
|
||||
}
|
||||
|
||||
func NewHealthHandler(r router.Router, server Server) Handler {
|
||||
func NewHealthHandler(r router.Router, server Server, database databasePinger) Handler {
|
||||
return &HealthHandler{
|
||||
router: r,
|
||||
server: server,
|
||||
router: r,
|
||||
server: server,
|
||||
database: database,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,5 +41,11 @@ func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "server is not ready"))
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := h.database.Ping(ctx); err != nil {
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "database unavailable"))
|
||||
return
|
||||
}
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
|
||||
}
|
||||
|
||||
@@ -29,6 +29,8 @@ var defaultConfig = &Config{
|
||||
VersionTable: "versions",
|
||||
RunMigrations: false,
|
||||
MaxConnections: 10,
|
||||
ConnectTimeout: 500 * time.Millisecond,
|
||||
QueryTimeout: 2 * time.Second,
|
||||
},
|
||||
Redis: &Redis{
|
||||
Host: "localhost",
|
||||
@@ -39,7 +41,7 @@ var defaultConfig = &Config{
|
||||
},
|
||||
JWT: &JWT{
|
||||
AccessTokenLifetime: 4 * time.Hour,
|
||||
RefreshTokenLifetime: 24 * time.Hour,
|
||||
RefreshTokenLifetime: time.Hour,
|
||||
PublicKeyPath: "certs/private.pem",
|
||||
PrivateKeyPath: "certs/public.pem",
|
||||
},
|
||||
|
||||
@@ -2,6 +2,8 @@ package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
@@ -16,9 +18,9 @@ type JWT struct {
|
||||
|
||||
func (c *JWT) Validate() error {
|
||||
switch {
|
||||
case c.AccessTokenLifetime == 0:
|
||||
case c.AccessTokenLifetime <= 0:
|
||||
return wrapValidationError("jwt", errors.New("access_token_lifetime cannot be empty"))
|
||||
case c.RefreshTokenLifetime == 0:
|
||||
case c.RefreshTokenLifetime <= 0:
|
||||
return wrapValidationError("jwt", errors.New("refresh_token_lifetime cannot be empty"))
|
||||
case c.PrivateKeyPath == "":
|
||||
return wrapValidationError("jwt", errors.New("private_key_path cannot be empty"))
|
||||
@@ -32,7 +34,20 @@ func (c *JWT) Validate() error {
|
||||
func (c *JWT) loadConfig(v *viper.Viper) error {
|
||||
v.SetEnvPrefix("JWT")
|
||||
c.AccessTokenLifetime = v.GetDuration("ACCESS_TOKEN_LIFETIME")
|
||||
c.RefreshTokenLifetime = v.GetDuration("REFRESH_TOKEN_LIFETIME")
|
||||
c.RefreshTokenLifetime = time.Hour
|
||||
if value := os.Getenv("SESSION_TTL_SECONDS"); value != "" {
|
||||
seconds, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || seconds <= 0 || seconds > int64((1<<63-1)/time.Second) {
|
||||
return wrapValidationError("session", errors.New("SESSION_TTL_SECONDS must be a positive integer duration in seconds"))
|
||||
}
|
||||
c.RefreshTokenLifetime = time.Duration(seconds) * time.Second
|
||||
} else if legacy := v.GetString("REFRESH_TOKEN_LIFETIME"); legacy != "" {
|
||||
duration, err := time.ParseDuration(legacy)
|
||||
if err != nil {
|
||||
return wrapValidationError("jwt", errors.New("invalid refresh_token_lifetime"))
|
||||
}
|
||||
c.RefreshTokenLifetime = duration
|
||||
}
|
||||
c.PublicKeyPath = v.GetString("PUBLIC_KEY_PATH")
|
||||
c.PrivateKeyPath = v.GetString("PRIVATE_KEY_PATH")
|
||||
return nil
|
||||
|
||||
@@ -3,6 +3,8 @@ package config
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
@@ -20,6 +22,8 @@ type Postgres struct {
|
||||
VersionTable string
|
||||
RunMigrations bool
|
||||
MaxConnections int
|
||||
ConnectTimeout time.Duration
|
||||
QueryTimeout time.Duration
|
||||
}
|
||||
|
||||
func (c *Postgres) Validate() error {
|
||||
@@ -36,13 +40,21 @@ func (c *Postgres) Validate() error {
|
||||
return wrapValidationError("postgres", errors.New("database cannot be empty"))
|
||||
case c.VersionTable == "":
|
||||
return wrapValidationError("postgres", errors.New("version_table name cannot be empty"))
|
||||
case c.MaxConnections == 0:
|
||||
return wrapValidationError("postgres", errors.New("max_connections cannot be empty"))
|
||||
case c.MaxConnections <= 0 || int64(c.MaxConnections) > math.MaxInt32:
|
||||
return wrapValidationError("postgres", errors.New("max_connections must be between 1 and 2147483647"))
|
||||
case c.ConnectTimeout <= 0:
|
||||
return wrapValidationError("postgres", errors.New("connect_timeout must be positive"))
|
||||
case c.QueryTimeout < time.Millisecond:
|
||||
return wrapValidationError("postgres", errors.New("query_timeout must be at least 1ms"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Postgres) GetMaxConnections() int32 { return int32(c.MaxConnections) }
|
||||
func (c *Postgres) GetConnectTimeout() time.Duration { return c.ConnectTimeout }
|
||||
func (c *Postgres) GetQueryTimeout() time.Duration { return c.QueryTimeout }
|
||||
|
||||
func (c *Postgres) GetVersionTableName() string {
|
||||
if c == nil {
|
||||
return ""
|
||||
@@ -74,6 +86,8 @@ func (c *Postgres) loadConfig(v *viper.Viper) error {
|
||||
c.VersionTable = v.GetString("VERSION_TABLE")
|
||||
c.RunMigrations = v.GetBool("RUN_MIGRATIONS")
|
||||
c.MaxConnections = v.GetInt("MAX_CONNECTIONS")
|
||||
c.ConnectTimeout = v.GetDuration("CONNECT_TIMEOUT")
|
||||
c.QueryTimeout = v.GetDuration("QUERY_TIMEOUT")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -88,6 +102,8 @@ func (c *Postgres) copy() *Postgres {
|
||||
Password: c.Password,
|
||||
Database: c.Database,
|
||||
MaxConnections: c.MaxConnections,
|
||||
ConnectTimeout: c.ConnectTimeout,
|
||||
QueryTimeout: c.QueryTimeout,
|
||||
RunMigrations: c.RunMigrations,
|
||||
VersionTable: c.VersionTable,
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ const (
|
||||
CodeBadRequest Code = iota
|
||||
// CodePayloadTooLarge = {AppError: REQUEST_ENTITY_TOO_LARGE, HTTP:413}
|
||||
CodePayloadTooLarge
|
||||
// CodeValidation = {AppError: VALIDATION, HTTP:422}
|
||||
// CodeValidation = {AppError: VALIDATION, HTTP:400}
|
||||
CodeValidation
|
||||
// CodeUnauthorized = {AppError: UNAUTHORIZED, HTTP:401}
|
||||
CodeUnauthorized
|
||||
@@ -155,7 +155,7 @@ var (
|
||||
CodeConflict: http.StatusConflict,
|
||||
CodePayloadTooLarge: http.StatusRequestEntityTooLarge,
|
||||
CodeTooManyRequests: http.StatusTooManyRequests,
|
||||
CodeValidation: http.StatusUnprocessableEntity,
|
||||
CodeValidation: http.StatusBadRequest,
|
||||
CodeTimeout: http.StatusGatewayTimeout,
|
||||
CodeInternal: http.StatusInternalServerError,
|
||||
CodeServiceUnavailable: http.StatusServiceUnavailable,
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
@@ -27,7 +31,21 @@ func (e *AppError) handlePostgres() {
|
||||
return
|
||||
}
|
||||
|
||||
var networkError net.Error
|
||||
var connectError *pgconn.ConnectError
|
||||
if errors.Is(e.err, context.DeadlineExceeded) || errors.Is(e.err, io.EOF) ||
|
||||
errors.Is(e.err, io.ErrUnexpectedEOF) || errors.As(e.err, &networkError) || errors.As(e.err, &connectError) {
|
||||
e.code = CodeServiceUnavailable
|
||||
e.msg = "database unavailable"
|
||||
return
|
||||
}
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](e.err); ok {
|
||||
if strings.HasPrefix(pgErr.Code, "08") || pgErr.Code == "57014" ||
|
||||
pgErr.Code == "57P01" || pgErr.Code == "57P02" || pgErr.Code == "57P03" || pgErr.Code == "53300" {
|
||||
e.code = CodeServiceUnavailable
|
||||
e.msg = "database unavailable"
|
||||
return
|
||||
}
|
||||
e.meta[PgErrorCode] = pgErr.Code
|
||||
e.code = CodeFromPostgres(pgErr.Code)
|
||||
return
|
||||
|
||||
@@ -28,6 +28,7 @@ type claimsParseFunc func(token *dto.Token) (*jwtClaims, error)
|
||||
type jwtClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
|
||||
Nonce string `json:"nonce,omitempty"`
|
||||
IsAccess bool `json:"is_access"`
|
||||
Role role.Role `json:"role"`
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
@@ -127,7 +129,12 @@ func (p *provider) createTokenForUser(userID uuid.UUID, isAccess bool, role role
|
||||
} else {
|
||||
tokenExpiresAt = now.Add(p.refreshLifetime)
|
||||
}
|
||||
var nonce [32]byte
|
||||
if _, err := rand.Read(nonce[:]); err != nil {
|
||||
return nil, fmt.Errorf("generate token nonce: %w", err)
|
||||
}
|
||||
claims := &jwtClaims{
|
||||
Nonce: base64.RawURLEncoding.EncodeToString(nonce[:]),
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: userID.String(),
|
||||
ExpiresAt: jwt.NewNumericDate(tokenExpiresAt),
|
||||
|
||||
@@ -87,7 +87,14 @@ func (m *migrator) Configure(ctx context.Context) error {
|
||||
}
|
||||
|
||||
func (m *migrator) Close(ctx context.Context) error {
|
||||
return m.closeConn(ctx)
|
||||
if m.conn == nil || m.closed {
|
||||
return nil
|
||||
}
|
||||
if err := m.closeConn(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
m.closed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *migrator) Start(ctx context.Context) error {
|
||||
@@ -118,19 +125,7 @@ func (m *migrator) Start(ctx context.Context) error {
|
||||
}
|
||||
|
||||
func (m *migrator) Stop(ctx context.Context) error {
|
||||
if !m.cfg.Postgres.GetRunMigrations() {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !m.closed {
|
||||
err := m.conn.Close(ctx)
|
||||
if err != nil {
|
||||
slog.Error("failed close connection to database", "error", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
return m.Close(ctx)
|
||||
}
|
||||
|
||||
func (m *migrator) loadMigrations() (err error) {
|
||||
@@ -144,6 +139,7 @@ func (m *migrator) loadMigrations() (err error) {
|
||||
}
|
||||
|
||||
func (m *migrator) initConn(ctx context.Context) (err error) {
|
||||
m.closed = false
|
||||
m.conn, err = pgx.Connect(ctx, m.cfg.Postgres.GetURI())
|
||||
if err != nil {
|
||||
slog.Error("failed to create connection to database", "error", err)
|
||||
|
||||
@@ -3,6 +3,8 @@ package postgres
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
@@ -15,6 +17,11 @@ type ConfigWithLog interface {
|
||||
GetLogLevel() string
|
||||
}
|
||||
|
||||
type ConfigWithTimeouts interface {
|
||||
GetConnectTimeout() time.Duration
|
||||
GetQueryTimeout() time.Duration
|
||||
}
|
||||
|
||||
type ConfigWithMaxConn interface {
|
||||
GetMaxConnections() int32
|
||||
}
|
||||
@@ -47,6 +54,14 @@ func New(cfg MigrationConfig, afterConnect ...AfterConnect) *pgxpool.Pool {
|
||||
}
|
||||
|
||||
addMaxConnectionsToCfg(cfg, poolConfig)
|
||||
if timeoutCfg, ok := cfg.(ConfigWithTimeouts); ok {
|
||||
poolConfig.ConnConfig.ConnectTimeout = timeoutCfg.GetConnectTimeout()
|
||||
poolConfig.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(timeoutCfg.GetQueryTimeout().Milliseconds(), 10)
|
||||
}
|
||||
poolConfig.ConnConfig.RuntimeParams["application_name"] = "mtusi-api"
|
||||
slog.Info("postgres_pool_config", "max_conns", poolConfig.MaxConns,
|
||||
"connect_timeout", poolConfig.ConnConfig.ConnectTimeout,
|
||||
"statement_timeout_ms", poolConfig.ConnConfig.RuntimeParams["statement_timeout"])
|
||||
|
||||
poolConfig.ConnConfig.Tracer = &tracelog.TraceLog{
|
||||
Logger: pgxslog.NewLogger(slog.Default()),
|
||||
|
||||
@@ -69,6 +69,9 @@ func JSONError(ctx context.Context, w http.ResponseWriter, err error) {
|
||||
}
|
||||
w.Header().Set(headers.HeaderRequestID, requestId.String())
|
||||
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
err = apperr.Wrap(err, apperr.CodeServiceUnavailable, "request deadline exceeded")
|
||||
}
|
||||
appErr := apperr.As(err)
|
||||
if appErr == nil {
|
||||
appErr = apperr.As(apperr.New(apperr.CodeInternal, "internal server error"))
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RequestTimeout bounds database work and waiting for a pooled connection.
|
||||
func RequestTimeout(timeout time.Duration) Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), timeout)
|
||||
defer cancel()
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user