forked from mtusi2026/mtusi2026lab2
Проверка и завершение требований уровней «3» и «4»
This commit is contained in:
@@ -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