Реализация на 5

This commit is contained in:
Grbisba
2026-11-06 13:11:04 +03:00
parent 8d44c74535
commit 711754bbcd
27 changed files with 5999 additions and 116 deletions
+13 -5
View File
@@ -10,9 +10,11 @@ import (
"time"
"gitea.privcloud.tech/mtusi2026/internal/adapter/controller/http"
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/outside"
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/storage"
"gitea.privcloud.tech/mtusi2026/internal/config"
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
"gitea.privcloud.tech/mtusi2026/internal/pkg/cache"
"gitea.privcloud.tech/mtusi2026/internal/pkg/encrypting"
"gitea.privcloud.tech/mtusi2026/internal/pkg/migrator"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
@@ -39,10 +41,8 @@ func run() error {
return fmt.Errorf("load server config: %w", err)
}
pgx, err := postgres.New(cfg.Postgres)
if err != nil {
return fmt.Errorf("init postgres: %w", err)
}
pgx := postgres.New(cfg.Postgres)
rx := cache.New(cfg)
postgresMigrator := migrator.New(cfg)
tm := txmanager.New(pgx)
provider := jwtprovider.New(cfg)
@@ -53,9 +53,11 @@ func run() error {
refreshTokensRepo := storage.NewRefreshTokensRepo(pgx)
userRepo := storage.NewUsersRepo(pgx)
chatCache := outside.NewChatCache(rx)
authSvc := auth.New(provider, tm, encryptor, userRepo, refreshTokensRepo)
userSvc := user.New(encryptor, userRepo)
chatSvc := chat.New(tm, chatsRepo, messageRepo)
chatSvc := chat.New(tm, chatsRepo, messageRepo, chatCache)
httpRouter := router.New(
middleware.NewAuthMiddleware(authSvc),
@@ -80,6 +82,9 @@ func run() error {
if err = server.Start(ctx); err != nil {
return fmt.Errorf("start HTTP server: %w", err)
}
if err = rx.Start(ctx); err != nil {
slog.Warn("redis unavailable at startup; continuing without cache", "error", err)
}
slog.Info("HTTP server started", "address", cfg.Server.BindAddress())
<-ctx.Done()
@@ -91,6 +96,9 @@ func run() error {
if err = postgresMigrator.Close(shutdownCtx); err != nil {
return fmt.Errorf("close postgres migrator: %w", err)
}
if err = rx.Close(); err != nil {
return fmt.Errorf("close redis: %w", err)
}
return nil
}
+1 -1
View File
@@ -14,6 +14,7 @@ require (
github.com/spf13/viper v1.21.0
go.uber.org/multierr v1.11.0
golang.org/x/crypto v0.57.0
golang.org/x/sync v0.23.0
google.golang.org/grpc v1.85.0
)
@@ -51,7 +52,6 @@ require (
github.com/vgarvardt/pgx-google-uuid/v5 v5.6.0 // indirect
go.uber.org/atomic v1.12.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/sync v0.23.0 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/text v0.42.0 // indirect
)
@@ -2,9 +2,15 @@ package http
import (
"net/http"
"regexp"
"strings"
"unicode/utf8"
"github.com/google/uuid"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
@@ -29,6 +35,8 @@ func NewUserHandler(r router.Router, provider jwtprovider.Provider, v *validator
}
}
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func (h *UserHandler) RegisterRoutes() {
h.router.Public(http.MethodPost, "/api/v1/users", h.Create)
h.router.Private(http.MethodGet, "/api/v1/users/me", h.GetMe)
@@ -51,6 +59,17 @@ func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
toCreate.Password = *req.Password
}
if !usernamePattern.MatchString(req.Username) || !utf8.ValidString(req.DisplayName) ||
strings.TrimSpace(req.DisplayName) == "" || utf8.RuneCountInString(req.DisplayName) > 100 {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid user fields"))
return
}
passwordLen := utf8.RuneCountInString(toCreate.Password)
if !utf8.ValidString(toCreate.Password) || strings.TrimSpace(toCreate.Password) == "" || passwordLen < 12 || passwordLen > 128 {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid password"))
return
}
resp, err := h.user.Create(ctx, toCreate)
if err != nil {
framework.JSONError(ctx, w, err)
@@ -74,6 +93,11 @@ func (h *UserHandler) GetMe(w http.ResponseWriter, r *http.Request) {
return
}
if userData.UserID == uuid.Nil {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid user id"))
return
}
resp, err := h.user.GetByID(ctx, userData.UserID)
if err != nil {
framework.JSONError(ctx, w, err)
@@ -0,0 +1,78 @@
package outside
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/cache"
)
const (
// chatRedisKey equals "chat:{chat_id}" path
chatRedisKey = "chat:%s"
)
type ChatCache struct {
client *cache.Client
}
func NewChatCache(client *cache.Client) *ChatCache {
return &ChatCache{
client: client,
}
}
type chat struct {
ID uuid.UUID `json:"id"`
Title string `json:"title"`
MemberIDs []uuid.UUID `json:"member_ids"`
CreatedAt time.Time `json:"created_at"`
}
func (r *ChatCache) Create(ctx context.Context, req dto.Chat) error {
data, err := json.Marshal(chat{
ID: req.ID,
Title: req.Title,
MemberIDs: req.MemberIDs,
CreatedAt: req.CreatedAt,
})
if err != nil {
return apperr.Wrap(err, apperr.CodeInternal, "failed to marshal chat cache")
}
ctx, cancel := context.WithTimeout(ctx, cache.OperationTimeout)
defer cancel()
err = r.client.Set(ctx, fmt.Sprintf(chatRedisKey, req.ID), data, 0).Err()
if err != nil {
return apperr.WrapRedis(err, "failed to create chat cache")
}
return nil
}
func (r *ChatCache) Get(ctx context.Context, chatID uuid.UUID) (*dto.Chat, error) {
ctx, cancel := context.WithTimeout(ctx, cache.OperationTimeout)
defer cancel()
data, err := r.client.Get(ctx, fmt.Sprintf(chatRedisKey, chatID.String())).Bytes()
if err != nil {
return nil, apperr.WrapRedis(err, "failed to read chat cache")
}
var item chat
if err = json.Unmarshal(data, &item); err != nil {
return nil, apperr.Wrap(err, apperr.CodeInternal, "failed to unmarshal chat cache")
}
return &dto.Chat{
ID: item.ID,
Title: item.Title,
MemberIDs: item.MemberIDs,
CreatedAt: item.CreatedAt,
}, nil
}
+12 -4
View File
@@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"net"
"time"
"github.com/redis/go-redis/v9"
"github.com/spf13/viper"
@@ -33,10 +34,17 @@ func (c *Redis) BuildRedisOptions() *redis.Options {
return nil
}
return &redis.Options{
Addr: net.JoinHostPort(c.Host, fmt.Sprintf("%d", c.Port)),
Username: c.Username,
Password: c.Password,
DB: c.DB,
Addr: net.JoinHostPort(c.Host, fmt.Sprintf("%d", c.Port)),
Username: c.Username,
Password: c.Password,
DB: c.DB,
DialTimeout: 200 * time.Millisecond,
ReadTimeout: 200 * time.Millisecond,
WriteTimeout: 200 * time.Millisecond,
PoolTimeout: 200 * time.Millisecond,
MaxRetries: -1,
DialerRetries: 1,
ContextTimeoutEnabled: true,
}
}
+43
View File
@@ -0,0 +1,43 @@
package cache
import (
"context"
"time"
"github.com/redis/go-redis/v9"
"gitea.privcloud.tech/mtusi2026/internal/config"
)
const defaultRedisPort = 6379
// OperationTimeout bounds each optional cache operation independently of the request.
const OperationTimeout = 300 * time.Millisecond
type Client struct {
*redis.Client
}
func New(cfg *config.Config) *Client {
if cfg.Redis.Port == 0 {
cfg.Redis.Port = defaultRedisPort
}
return &Client{
Client: redis.NewClient(cfg.Redis.BuildRedisOptions()),
}
}
func (c *Client) Ping(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, OperationTimeout)
defer cancel()
return c.Client.Ping(ctx).Err()
}
func (c *Client) Start(ctx context.Context) error {
return c.Ping(ctx)
}
func (c *Client) Stop(_ context.Context) error {
return c.Client.Close()
}
+4 -4
View File
@@ -33,7 +33,7 @@ func addMaxConnectionsToCfg(cfg any, poolCfg *pgxpool.Config) {
}
}
func New(cfg MigrationConfig, afterConnect ...AfterConnect) (*pgxpool.Pool, error) {
func New(cfg MigrationConfig, afterConnect ...AfterConnect) *pgxpool.Pool {
lvl := getLevelFromConfig(cfg)
if len(afterConnect) == 0 {
@@ -43,7 +43,7 @@ func New(cfg MigrationConfig, afterConnect ...AfterConnect) (*pgxpool.Pool, erro
poolConfig, err := pgxpool.ParseConfig(cfg.GetURI())
if err != nil {
slog.Error("failed to parse postgres config", "error", err)
return nil, errParseConfig
panic(err)
}
addMaxConnectionsToCfg(cfg, poolConfig)
@@ -61,11 +61,11 @@ func New(cfg MigrationConfig, afterConnect ...AfterConnect) (*pgxpool.Pool, erro
pool, err := pgxpool.NewWithConfig(context.Background(), poolConfig)
if err != nil {
slog.Error("failed to create postgres pool", "error", err)
return nil, errCreatingPool
panic(err)
}
slog.Info("successfully connected to postgres pool")
return pool, nil
return pool
}
func load(afterConnects ...AfterConnect) func(ctx context.Context, conn *pgx.Conn) error {
@@ -20,3 +20,8 @@ type messagesRepo interface {
GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error)
ListForChat(ctx context.Context, chatID uuid.UUID, page dto.PageQuery) ([]dto.Message, error)
}
type chatsCache interface {
Create(ctx context.Context, req dto.Chat) error
Get(ctx context.Context, chatID uuid.UUID) (*dto.Chat, error)
}
+75 -8
View File
@@ -3,11 +3,15 @@ package chat
import (
"bytes"
"context"
"errors"
"log/slog"
"slices"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/redis/go-redis/v9"
"golang.org/x/sync/singleflight"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
@@ -16,21 +20,26 @@ import (
var _ API = (*Chat)(nil)
const chatLoadTimeout = 2 * time.Second
type Chat struct {
tm *txmanager.TransactionManager
chatsRepo chatsRepo
messagesRepo messagesRepo
chatsCache chatsCache
loads singleflight.Group
}
func New(tm *txmanager.TransactionManager, chatsRepo chatsRepo, messagesRepo messagesRepo) *Chat {
return &Chat{tm: tm, chatsRepo: chatsRepo, messagesRepo: messagesRepo}
func New(tm *txmanager.TransactionManager, chatsRepo chatsRepo, messagesRepo messagesRepo, chatsCache chatsCache) *Chat {
return &Chat{
tm: tm,
chatsRepo: chatsRepo,
messagesRepo: messagesRepo,
chatsCache: chatsCache,
}
}
func (c *Chat) CreateChat(ctx context.Context, req dto.CreateChat) (*dto.Chat, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
seen := make(map[uuid.UUID]struct{}, len(req.MemberIDs))
for _, id := range req.MemberIDs {
if id == uuid.Nil {
@@ -67,10 +76,68 @@ func (c *Chat) CreateChat(ctx context.Context, req dto.CreateChat) (*dto.Chat, e
}
func (c *Chat) GetForMember(ctx context.Context, req dto.ChatMember) (*dto.Chat, error) {
chat, err := c.chatsRepo.GetForMember(ctx, req)
if err != nil {
if err := ctx.Err(); err != nil {
return nil, err
}
if chat, err := c.cachedChat(ctx, req.ChatID); err == nil {
return chatForMember(chat, req.UserID)
}
// Repository results depend on membership: never share a user's 404 with
// another user requesting the same chat.
key := req.ChatID.String() + ":" + req.UserID.String()
result := c.loads.DoChan(key, func() (any, error) {
// One client disconnecting must not cancel the other clients' load.
loadCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), chatLoadTimeout)
defer cancel()
// A previous load may have populated Redis after our initial miss.
if chat, err := c.cachedChat(loadCtx, req.ChatID); err == nil {
return chatForMember(chat, req.UserID)
}
slog.Info("chat_db_lookup", "chat_id", req.ChatID)
chat, err := c.chatsRepo.GetForMember(loadCtx, req)
if err != nil {
return nil, err
}
if err = c.chatsCache.Create(loadCtx, *chat); err != nil {
slog.Warn("failed to cache chat", "chat_id", req.ChatID, "error", err)
}
return chat, nil
})
select {
case <-ctx.Done():
return nil, ctx.Err()
case loaded := <-result:
if err := ctx.Err(); err != nil {
return nil, err
}
if loaded.Err != nil {
return nil, loaded.Err
}
return chatForMember(loaded.Val.(*dto.Chat), req.UserID)
}
}
func (c *Chat) cachedChat(ctx context.Context, chatID uuid.UUID) (*dto.Chat, error) {
chat, err := c.chatsCache.Get(ctx, chatID)
switch {
case err == nil:
slog.Info("chat_cache_hit", "chat_id", chatID)
case errors.Is(err, redis.Nil):
slog.Info("chat_cache_miss", "chat_id", chatID)
default:
slog.Warn("chat_cache_read_error", "chat_id", chatID, "error", err)
}
return chat, err
}
func chatForMember(chat *dto.Chat, userID uuid.UUID) (*dto.Chat, error) {
if !slices.Contains(chat.MemberIDs, userID) {
return nil, apperr.New(apperr.CodeNotFound, "chat not found")
}
return chat, nil
}
+3 -3
View File
@@ -9,7 +9,7 @@ import (
)
type API interface {
Create(ctx context.Context, req dto.CreateUser) (dto.User, error)
GetByID(ctx context.Context, id uuid.UUID) (dto.User, error)
GetByUsername(ctx context.Context, username string) (dto.User, error)
Create(ctx context.Context, req dto.CreateUser) (*dto.User, error)
GetByID(ctx context.Context, id uuid.UUID) (*dto.User, error)
GetByUsername(ctx context.Context, username string) (*dto.User, error)
}
+24 -54
View File
@@ -2,10 +2,7 @@ package user
import (
"context"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
@@ -15,8 +12,7 @@ import (
)
var (
_ API = (*User)(nil)
usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
_ API = (*User)(nil)
)
type User struct {
@@ -28,70 +24,44 @@ func New(encryptor encrypting.Encryptor, usersRepo userRepo) *User {
return &User{encryptor: encryptor, usersRepo: usersRepo}
}
func (u *User) Create(ctx context.Context, req dto.CreateUser) (dto.User, error) {
if err := ctx.Err(); err != nil {
return dto.User{}, err
}
if !usernamePattern.MatchString(req.Username) || !utf8.ValidString(req.DisplayName) ||
strings.TrimSpace(req.DisplayName) == "" || utf8.RuneCountInString(req.DisplayName) > 100 {
return dto.User{}, apperr.New(apperr.CodeBadRequest, "invalid user fields")
}
passwordLen := utf8.RuneCountInString(req.Password)
if !utf8.ValidString(req.Password) || strings.TrimSpace(req.Password) == "" || passwordLen < 12 || passwordLen > 128 {
return dto.User{}, apperr.New(apperr.CodeBadRequest, "invalid password")
}
id, err := uuid.NewRandom()
if err != nil {
return dto.User{}, apperr.Wrap(err, apperr.CodeInternal, "failed to generate user id")
}
func (u *User) Create(ctx context.Context, req dto.CreateUser) (*dto.User, error) {
hash, err := u.encryptor.EncryptSecretUsingArgon2id(ctx, req.Password)
if err != nil {
if ctx.Err() != nil {
return dto.User{}, ctx.Err()
}
return dto.User{}, apperr.Wrap(err, apperr.CodeInternal, "failed to hash password")
return nil, apperr.Wrap(err, apperr.CodeInternal, "failed to hash password")
}
now := time.Now().Truncate(time.Microsecond)
user := dto.User{ID: id, Username: req.Username, DisplayName: req.DisplayName, CreatedAt: now}
user := dto.User{
ID: uuid.New(),
Username: req.Username,
DisplayName: req.DisplayName,
CreatedAt: time.Now().Truncate(time.Microsecond),
}
if err = u.usersRepo.Create(ctx, dto.CreateStoredUser{
ID: user.ID,
Username: user.Username,
DisplayName: user.DisplayName,
PasswordHash: hash,
CreatedAt: now,
UpdatedAt: now,
CreatedAt: user.CreatedAt,
UpdatedAt: user.CreatedAt,
}); err != nil {
return dto.User{}, err
return nil, err
}
return &user, nil
}
func (u *User) GetByID(ctx context.Context, id uuid.UUID) (*dto.User, error) {
user, err := u.usersRepo.GetByID(ctx, id)
if err != nil {
return nil, err
}
return user, nil
}
func (u *User) GetByID(ctx context.Context, id uuid.UUID) (dto.User, error) {
if err := ctx.Err(); err != nil {
return dto.User{}, err
}
if id == uuid.Nil {
return dto.User{}, apperr.New(apperr.CodeBadRequest, "invalid user id")
}
user, err := u.usersRepo.GetByID(ctx, id)
if err != nil {
return dto.User{}, err
}
return *user, nil
}
func (u *User) GetByUsername(ctx context.Context, username string) (dto.User, error) {
if err := ctx.Err(); err != nil {
return dto.User{}, err
}
if !usernamePattern.MatchString(username) {
return dto.User{}, apperr.New(apperr.CodeBadRequest, "invalid username")
}
func (u *User) GetByUsername(ctx context.Context, username string) (*dto.User, error) {
user, err := u.usersRepo.GetByUsername(ctx, username)
if err != nil {
return dto.User{}, err
return nil, err
}
return *user, nil
return user, nil
}