Перенес необходимые изменения из лабораторной работы №2

This commit is contained in:
Grbisba
2026-11-06 14:27:27 +03:00
parent 0ab3a341aa
commit 4c066ff191
92 changed files with 7156 additions and 7 deletions
@@ -0,0 +1,88 @@
package http
import (
"net/http"
"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/rest/framework"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
"gitea.privcloud.tech/mtusi2026/internal/service/auth"
)
type AuthHandler struct {
router router.Router
auth auth.API
}
func NewAuthHandler(r router.Router, api auth.API) Handler {
return &AuthHandler{
router: r,
auth: api,
}
}
func (h *AuthHandler) RegisterRoutes() {
h.router.Public(http.MethodPost, "/api/v1/auth/sessions", h.Login)
h.router.Private(http.MethodDelete, "/api/v1/auth/sessions/current", h.Logout)
}
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
username, password, ok := r.BasicAuth()
if !ok || username == "" || password == "" {
w.Header().Set(
"WWW-Authenticate",
`Basic realm="messenger", charset="UTF-8"`,
)
framework.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "invalid credentials"))
return
}
resp, err := h.auth.Login(ctx, dto.Login{
Username: username,
Password: password,
})
if err != nil {
if apperr.HTTPStatusFromError(err) == http.StatusUnauthorized {
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
}
framework.JSONError(ctx, w, err)
return
}
framework.JSONResponse(w, http.StatusCreated, contracts.Session{
ExpiresAt: resp.ExpiresAt,
Token: resp.Tokens.RefreshToken.Payload,
TokenType: resp.TokenType,
User: contracts.User{
CreatedAt: resp.User.CreatedAt,
DisplayName: resp.User.DisplayName,
Id: resp.User.ID,
Username: resp.User.Username,
},
})
}
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
token, exists := framework.Token(r)
if !exists {
framework.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "missing token in header"))
return
}
err := h.auth.Logout(ctx, dto.RefreshToken{
Payload: token,
})
if err != nil {
framework.JSONError(ctx, w, err)
return
}
framework.JSONResponse(w, http.StatusNoContent, nil)
}
@@ -0,0 +1,261 @@
package http
import (
"net/http"
"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"
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
"gitea.privcloud.tech/mtusi2026/internal/service/chat"
)
type ChatHandler struct {
router router.Router
provider jwtprovider.Provider
validator *validator.ValidatorImpl
chat chat.API
}
func NewChatHandler(r router.Router, provider jwtprovider.Provider, v *validator.ValidatorImpl, api chat.API) Handler {
return &ChatHandler{
router: r,
provider: provider,
validator: v,
chat: api,
}
}
func (h *ChatHandler) RegisterRoutes() {
h.router.Private(http.MethodPost, "/api/v1/chats", h.Create)
h.router.Private(http.MethodGet, "/api/v1/chats", h.Get)
h.router.Private(http.MethodGet, "/api/v1/chats/{chat_id}", h.GetByID)
h.router.Private(http.MethodPost, "/api/v1/chats/{chat_id}/messages", h.SendMessage)
h.router.Private(http.MethodGet, "/api/v1/chats/{chat_id}/messages", h.GetMessages)
}
func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userData, err := framework.ParseToken(r, h.provider)
if err != nil {
framework.JSONError(ctx, w, err)
return
}
var req contracts.CreateChat
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
return
}
if userData.UserID == uuid.Nil ||
!validText(req.Title, 100) ||
len(req.MemberIds) < 1 ||
len(req.MemberIds) > 100 {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid chat fields"))
return
}
resp, err := h.chat.CreateChat(ctx, dto.CreateChat{
CreatorID: userData.UserID,
Title: req.Title,
MemberIDs: req.MemberIds,
})
if err != nil {
framework.JSONError(ctx, w, err)
return
}
framework.JSONResponse(w, http.StatusCreated, contracts.Chat{
Id: resp.ID,
Title: resp.Title,
MemberIds: resp.MemberIDs,
CreatedAt: resp.CreatedAt,
})
}
func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userData, err := framework.ParseToken(r, h.provider)
if err != nil {
framework.JSONError(ctx, w, err)
return
}
limit, afterID, ok := framework.PageParams(w, r)
if !ok {
return
}
if userData.UserID == uuid.Nil {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid user id"))
return
}
if afterID != nil && *afterID == uuid.Nil {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid cursor"))
return
}
page, err := h.chat.ListForMember(ctx, dto.ChatFilters{
UserID: userData.UserID,
Limit: limit,
AfterID: afterID,
})
if err != nil {
framework.JSONError(ctx, w, err)
return
}
items := make([]contracts.Chat, 0, len(page.Items))
for _, item := range page.Items {
items = append(items, contracts.Chat{
CreatedAt: item.CreatedAt,
Id: item.ID,
MemberIds: item.MemberIDs,
Title: item.Title,
})
}
framework.JSONResponse(w, http.StatusOK, contracts.ChatPage{
Items: items,
NextCursor: cursorString(page.NextCursorID),
})
}
func (h *ChatHandler) GetByID(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userData, err := framework.ParseToken(r, h.provider)
if err != nil {
framework.JSONError(ctx, w, err)
return
}
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
if err != nil {
return
}
resp, err := h.chat.GetForMember(ctx, dto.ChatMember{
UserID: userData.UserID,
ChatID: chatID,
})
if err != nil {
framework.JSONError(ctx, w, err)
return
}
framework.JSONResponse(w, http.StatusOK, contracts.Chat{
CreatedAt: resp.CreatedAt,
Id: resp.ID,
MemberIds: resp.MemberIDs,
Title: resp.Title,
})
}
func (h *ChatHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userData, err := framework.ParseToken(r, h.provider)
if err != nil {
framework.JSONError(ctx, w, err)
return
}
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
if err != nil {
return
}
var req contracts.CreateMessage
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
return
}
if !validText(req.Text, 4000) {
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid message text"))
return
}
message, err := h.chat.CreateMessage(ctx, dto.CreateMessage{
ChatID: chatID,
SenderID: userData.UserID,
Text: req.Text,
})
if err != nil {
framework.JSONError(ctx, w, err)
return
}
framework.JSONResponse(w, http.StatusCreated, contracts.Message{
Id: message.ID,
ChatId: message.ChatID,
SenderId: message.SenderID,
Text: message.Text,
CreatedAt: message.CreatedAt,
})
}
func (h *ChatHandler) GetMessages(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userData, err := framework.ParseToken(r, h.provider)
if err != nil {
framework.JSONError(ctx, w, err)
return
}
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
if err != nil {
return
}
limit, afterID, ok := framework.PageParams(w, r)
if !ok {
return
}
page, err := h.chat.ListForChat(ctx, dto.MessageFilters{
ChatID: chatID,
UserID: userData.UserID,
Limit: limit,
AfterID: afterID,
})
if err != nil {
framework.JSONError(ctx, w, err)
return
}
items := make([]contracts.Message, 0, len(page.Items))
for _, message := range page.Items {
items = append(items, contracts.Message{
Id: message.ID,
ChatId: message.ChatID,
SenderId: message.SenderID,
Text: message.Text,
CreatedAt: message.CreatedAt,
})
}
framework.JSONResponse(w, http.StatusOK, contracts.MessagePage{Items: items, NextCursor: cursorString(page.NextCursorID)})
}
func cursorString(id *uuid.UUID) *string {
if id == nil {
return nil
}
value := id.String()
return &value
}
func validText(value string, maxLength int) bool {
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxLength
}
@@ -0,0 +1,101 @@
package http
import (
"context"
"errors"
"log/slog"
"net"
"net/http"
"sync/atomic"
"gitea.privcloud.tech/mtusi2026/internal/config"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
)
type Server interface {
ShouldBeRunning() bool
Ready() bool
Start(ctx context.Context) error
Stop(ctx context.Context) error
}
type server struct {
server http.Server
cfg *config.Server
ready atomic.Bool
}
func New(cfg *config.Config, router router.Router) Server {
s := server{
server: http.Server{
Addr: cfg.Server.BindAddress(),
Handler: router,
ReadTimeout: cfg.Server.ReadTimeout,
WriteTimeout: cfg.Server.WriteTimeout,
IdleTimeout: cfg.Server.IdleTimeout,
},
cfg: cfg.Server,
ready: atomic.Bool{},
}
if err := s.validate(); err != nil {
panic(err)
}
return &s
}
func (s *server) Start(_ context.Context) error {
if !s.ShouldBeRunning() {
slog.Info("server should not be running: skip starting")
return nil
}
listener, err := net.Listen("tcp", s.server.Addr)
if err != nil {
return err
}
s.ready.Store(true)
go func() {
defer s.ready.Store(false)
if err := s.server.Serve(listener); err != nil &&
!errors.Is(err, http.ErrServerClosed) {
slog.Error("rest server failed", "error", err)
}
}()
return nil
}
func (s *server) Stop(ctx context.Context) error {
if !s.ShouldBeRunning() {
slog.Info("server should not be running: skip stopping")
return nil
}
slog.Info("shutting down rest server...", "address", s.server.Addr)
s.ready.Store(false)
if err := s.server.Shutdown(ctx); err != nil {
slog.Error("rest server shutdown failed", "error", err)
return err
}
slog.Info("rest server shutdown successfully")
return nil
}
func (s *server) ShouldBeRunning() bool {
return s.cfg.Enabled
}
func (s *server) Ready() bool {
return s.ready.Load()
}
func (s *server) validate() error {
if s.cfg == nil {
slog.Error("failed to validate server: provided nil config")
return errors.New("failed to validate server: provided nil config")
}
slog.Info("server successfully validated")
return nil
}
@@ -0,0 +1,5 @@
package http
type Handler interface {
RegisterRoutes()
}
@@ -0,0 +1,51 @@
package http
import (
"context"
"net/http"
"time"
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
)
type databasePinger interface{ Ping(context.Context) error }
type HealthHandler struct {
router router.Router
server Server
database databasePinger
}
func NewHealthHandler(r router.Router, server Server, database databasePinger) Handler {
return &HealthHandler{
router: r,
server: server,
database: database,
}
}
func (h *HealthHandler) RegisterRoutes() {
h.router.Public(http.MethodGet, "/health/ready", h.Ready)
h.router.Public(http.MethodGet, "/health/live", h.Live)
}
func (h *HealthHandler) Live(w http.ResponseWriter, _ *http.Request) {
framework.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
}
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
if !h.server.Ready() {
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})
}
@@ -0,0 +1 @@
package http
@@ -0,0 +1,113 @@
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"
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
"gitea.privcloud.tech/mtusi2026/internal/service/user"
)
type UserHandler struct {
router router.Router
provider jwtprovider.Provider
validator *validator.ValidatorImpl
user user.API
}
func NewUserHandler(r router.Router, provider jwtprovider.Provider, v *validator.ValidatorImpl, api user.API) Handler {
return &UserHandler{
router: r,
provider: provider,
validator: v,
user: api,
}
}
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)
}
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var req contracts.CreateUser
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
return
}
toCreate := dto.CreateUser{
Username: req.Username,
DisplayName: req.DisplayName,
}
if req.Password != nil {
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)
return
}
framework.JSONResponse(w, http.StatusCreated, contracts.User{
CreatedAt: resp.CreatedAt,
DisplayName: resp.DisplayName,
Id: resp.ID,
Username: resp.Username,
})
}
func (h *UserHandler) GetMe(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userData, err := framework.ParseToken(r, h.provider)
if err != nil {
framework.JSONError(ctx, w, err)
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)
return
}
framework.JSONResponse(w, http.StatusOK, contracts.User{
CreatedAt: resp.CreatedAt,
DisplayName: resp.DisplayName,
Id: resp.ID,
Username: resp.Username,
})
}
@@ -0,0 +1,107 @@
package inmemory
import (
"log/slog"
"sync/atomic"
"unsafe"
)
type Cache[K comparable, V any] interface {
Name() string
GetAll() map[K]V
GetList() []V
Get(key K) (value V, ok bool)
Find(predicate func(K, V) bool) []V
}
type CopyAndWriteCache[K comparable, V any] struct {
name string
data unsafe.Pointer
}
func NewCopyAndWriteCache[K comparable, V any](
name string,
) *CopyAndWriteCache[K, V] {
c := CopyAndWriteCache[K, V]{
name: name,
}
emptyMap := make(map[K]V)
atomic.StorePointer(&c.data, unsafe.Pointer(&emptyMap))
slog.Info("cache initialized", "name", name)
return &c
}
func (c *CopyAndWriteCache[K, V]) Name() string {
return c.name
}
func (c *CopyAndWriteCache[K, V]) GetAll() map[K]V {
ptr := atomic.LoadPointer(&c.data)
if ptr == nil {
return make(map[K]V)
}
m := *(*map[K]V)(ptr)
out := make(map[K]V, len(m))
for k, v := range m {
out[k] = v
}
return out
}
func (c *CopyAndWriteCache[K, V]) GetList() []V {
records := c.GetAll()
out := make([]V, 0, len(records))
for _, record := range records {
out = append(out, record)
}
return out
}
func (c *CopyAndWriteCache[K, V]) Get(key K) (value V, ok bool) {
ptr := atomic.LoadPointer(&c.data)
if ptr == nil {
var zero V
return zero, false
}
m := *(*map[K]V)(ptr)
v, ok := m[key]
return v, ok
}
func (c *CopyAndWriteCache[K, V]) Find(predicate func(K, V) bool) []V {
ptr := atomic.LoadPointer(&c.data)
if ptr == nil {
return []V{}
}
m := *(*map[K]V)(ptr)
var result []V
for key, value := range m {
if predicate(key, value) {
result = append(result, value)
}
}
return result
}
func (c *CopyAndWriteCache[K, V]) Store(key K, value V) bool {
ptr := atomic.LoadPointer(&c.data)
if ptr == nil {
return false
}
m := *(*map[K]V)(ptr)
m[key] = value
return true
}
@@ -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
}
@@ -0,0 +1,91 @@
package storage
import (
"context"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
)
type ChatsRepo struct {
pool *pgxpool.Pool
}
func NewChatsRepo(pool *pgxpool.Pool) *ChatsRepo {
return &ChatsRepo{pool: pool}
}
func (r *ChatsRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.Chat) error {
const insertChat = `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`
if _, err := tx.Exec(ctx, insertChat, req.ID, req.Title, req.CreatedAt); err != nil {
return apperr.WrapPostgres(err, "failed to create chat")
}
const insertMembers = `INSERT INTO chat_members (chat_id, user_id)
SELECT $1, user_id FROM unnest($2::uuid[]) AS members(user_id)`
if _, err := tx.Exec(ctx, insertMembers, req.ID, req.MemberIDs); err != nil {
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
pgErr.Code == pgerrcode.ForeignKeyViolation && pgErr.ConstraintName == "chat_members_user_fk" {
return apperr.Wrap(err, apperr.CodeBadRequest, "unknown chat member")
}
return apperr.WrapPostgres(err, "failed to create chat members")
}
return nil
}
func (r *ChatsRepo) GetForMember(ctx context.Context, req dto.ChatMember) (*dto.Chat, error) {
const query = `SELECT c.id, c.title, c.created_at,
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id)
FROM chats c
WHERE c.id = $1
AND EXISTS (SELECT 1 FROM chat_members access WHERE access.chat_id = c.id AND access.user_id = $2)`
return scanChat(r.pool.QueryRow(ctx, query, req.ChatID, req.UserID))
}
func (r *ChatsRepo) ListForMember(ctx context.Context, userID uuid.UUID, page dto.PageQuery) ([]dto.Chat, error) {
query := `WITH page AS MATERIALIZED (
SELECT c.id, c.title, c.created_at
FROM chats c JOIN chat_members access ON access.chat_id = c.id
WHERE access.user_id = $1`
args := []any{userID, page.Limit}
if page.After != nil {
query += ` AND (c.created_at, c.id) > ($3, $4)`
args = append(args, page.After.CreatedAt, page.After.ID)
}
query += ` ORDER BY c.created_at, c.id LIMIT $2
)
SELECT p.id, p.title, p.created_at,
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = p.id ORDER BY m.user_id)
FROM page p ORDER BY p.created_at, p.id`
rows, err := r.pool.Query(ctx, query, args...)
if err != nil {
return nil, apperr.WrapPostgres(err, "failed to list chats")
}
defer rows.Close()
chats := make([]dto.Chat, 0)
for rows.Next() {
chat, err := scanChat(rows)
if err != nil {
return nil, err
}
chats = append(chats, *chat)
}
if err = rows.Err(); err != nil {
return nil, apperr.WrapPostgres(err, "failed to list chats")
}
return chats, nil
}
func scanChat(row pgx.Row) (*dto.Chat, error) {
var chat dto.Chat
if err := row.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
return nil, apperr.WrapPostgres(err, "failed to get chat")
}
return &chat, nil
}
@@ -0,0 +1,75 @@
package storage
import (
"context"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
)
type MessagesRepo struct {
pool *pgxpool.Pool
}
func NewMessagesRepo(pool *pgxpool.Pool) *MessagesRepo {
return &MessagesRepo{pool: pool}
}
func (r *MessagesRepo) Create(ctx context.Context, req dto.Message) error {
const query = `INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)`
if _, err := r.pool.Exec(ctx, query, req.ID, req.ChatID, req.SenderID, req.Text, req.CreatedAt); err != nil {
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
pgErr.Code == pgerrcode.ForeignKeyViolation && pgErr.ConstraintName == "messages_sender_member_fk" {
return apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
}
return apperr.WrapPostgres(err, "failed to create message")
}
return nil
}
func (r *MessagesRepo) GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error) {
const query = `SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 AND id = $2`
return scanMessage(r.pool.QueryRow(ctx, query, chatID, messageID))
}
func (r *MessagesRepo) ListForChat(ctx context.Context, chatID uuid.UUID, page dto.PageQuery) ([]dto.Message, error) {
query := `SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1`
args := []any{chatID, page.Limit}
if page.After != nil {
query += ` AND (created_at, id) > ($3, $4)`
args = append(args, page.After.CreatedAt, page.After.ID)
}
query += ` ORDER BY created_at, id LIMIT $2`
rows, err := r.pool.Query(ctx, query, args...)
if err != nil {
return nil, apperr.WrapPostgres(err, "failed to list messages")
}
defer rows.Close()
messages := make([]dto.Message, 0)
for rows.Next() {
message, err := scanMessage(rows)
if err != nil {
return nil, err
}
messages = append(messages, *message)
}
if err = rows.Err(); err != nil {
return nil, apperr.WrapPostgres(err, "failed to list messages")
}
return messages, nil
}
func scanMessage(row pgx.Row) (*dto.Message, error) {
var message dto.Message
if err := row.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt); err != nil {
return nil, apperr.WrapPostgres(err, "failed to get message")
}
return &message, nil
}
@@ -0,0 +1,193 @@
package storage
import (
"context"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
)
type RefreshTokensRepo struct {
pool *pgxpool.Pool
}
func NewRefreshTokensRepo(pool *pgxpool.Pool) *RefreshTokensRepo {
return &RefreshTokensRepo{
pool: pool,
}
}
func (r *RefreshTokensRepo) Create(ctx context.Context, req dto.StoredRefreshToken) error {
return r.create(ctx, r.pool, req)
}
func (r *RefreshTokensRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.StoredRefreshToken) error {
return r.create(ctx, tx, req)
}
func (r *RefreshTokensRepo) GetByID(ctx context.Context, id uuid.UUID) (*dto.StoredRefreshToken, error) {
return r.getByID(ctx, r.pool, id, false)
}
func (r *RefreshTokensRepo) GetByIDTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.StoredRefreshToken, error) {
return r.getByID(ctx, tx, id, false)
}
func (r *RefreshTokensRepo) GetByIDForUpdate(ctx context.Context, id uuid.UUID) (*dto.StoredRefreshToken, error) {
return r.getByID(ctx, r.pool, id, true)
}
func (r *RefreshTokensRepo) GetByIDForUpdateTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.StoredRefreshToken, error) {
return r.getByID(ctx, tx, id, true)
}
func (r *RefreshTokensRepo) Revoke(ctx context.Context, req dto.RevokeRefreshToken) error {
return r.revoke(ctx, r.pool, req)
}
func (r *RefreshTokensRepo) RevokeTx(ctx context.Context, tx pgx.Tx, req dto.RevokeRefreshToken) error {
return r.revoke(ctx, tx, req)
}
func (r *RefreshTokensRepo) RevokeAllByUserID(ctx context.Context, req dto.RevokeRefreshTokensByUserID) error {
return r.revokeAllByUserID(ctx, r.pool, req)
}
func (r *RefreshTokensRepo) RevokeAllByUserIDTx(ctx context.Context, tx pgx.Tx, req dto.RevokeRefreshTokensByUserID) error {
return r.revokeAllByUserID(ctx, tx, req)
}
func (r *RefreshTokensRepo) DeleteExpired(ctx context.Context) error {
const query = `
DELETE FROM refresh_tokens
WHERE expires_at < $1`
_, err := r.pool.Exec(ctx, query, time.Now())
if err != nil {
return apperr.WrapPostgres(err, "failed to delete expired refresh tokens")
}
return nil
}
func (r *RefreshTokensRepo) create(ctx context.Context, conn postgres.Conn, req dto.StoredRefreshToken) error {
const query = `INSERT INTO refresh_tokens (id,
user_id,
token_hash,
user_agent,
ip_address,
role,
expires_at,
created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`
ct, err := conn.Exec(
ctx,
query,
req.ID,
req.UserID,
req.TokenHash,
req.UserAgent,
req.IPAddress,
req.Role,
req.ExpiresAt,
req.CreatedAt,
)
if err != nil {
return apperr.WrapPostgres(err, "failed to create refresh token")
}
if ct.RowsAffected() == 0 {
return apperr.New(apperr.CodeAlreadyExists, "refresh token already exists")
}
return nil
}
func (r *RefreshTokensRepo) getByID(ctx context.Context, conn postgres.Conn, id uuid.UUID, lock bool) (*dto.StoredRefreshToken, error) {
const query = `SELECT id,
user_id,
token_hash,
user_agent,
ip_address,
role,
expires_at,
revoked_at,
created_at
FROM refresh_tokens
WHERE id = $1`
const queryLock = `SELECT id,
user_id,
token_hash,
user_agent,
ip_address,
role,
expires_at,
revoked_at,
created_at
FROM refresh_tokens
WHERE id = $1 FOR UPDATE`
use := query
if lock {
use = queryLock
}
var token dto.StoredRefreshToken
err := conn.QueryRow(ctx, use, id).Scan(
&token.ID,
&token.UserID,
&token.TokenHash,
&token.UserAgent,
&token.IPAddress,
&token.Role,
&token.ExpiresAt,
&token.RevokedAt,
&token.CreatedAt,
)
if err != nil {
return nil, apperr.WrapPostgres(err, "failed to get refresh by id")
}
return &token, nil
}
func (r *RefreshTokensRepo) revoke(ctx context.Context, conn postgres.Conn, req dto.RevokeRefreshToken) error {
const query = `
UPDATE refresh_tokens
SET revoked_at = $2
WHERE id = $1
AND revoked_at IS NULL`
ct, err := conn.Exec(ctx, query, req.ID, req.RevokedAt)
if err != nil {
return apperr.WrapPostgres(err, "failed to revoke refresh token")
}
if ct.RowsAffected() == 0 {
return apperr.New(apperr.CodeNotFound, "refresh token not found")
}
return nil
}
func (r *RefreshTokensRepo) revokeAllByUserID(ctx context.Context, conn postgres.Conn, req dto.RevokeRefreshTokensByUserID) error {
const query = `
UPDATE refresh_tokens
SET revoked_at = $2
WHERE user_id = $1
AND revoked_at IS NULL`
_, err := conn.Exec(ctx, query, req.UserID, req.RevokedAt)
if err != nil {
return apperr.WrapPostgres(err, "failed to revoke refresh tokens")
}
return nil
}
@@ -0,0 +1,103 @@
package storage
import (
"context"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
)
type UsersRepo struct {
pool *pgxpool.Pool
}
func NewUsersRepo(pool *pgxpool.Pool) *UsersRepo {
return &UsersRepo{pool: pool}
}
func (r *UsersRepo) Create(ctx context.Context, req dto.CreateStoredUser) error {
return r.create(ctx, r.pool, req)
}
func (r *UsersRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.CreateStoredUser) error {
return r.create(ctx, tx, req)
}
func (r *UsersRepo) GetByID(ctx context.Context, id uuid.UUID) (*dto.User, error) {
return r.getByID(ctx, r.pool, id)
}
func (r *UsersRepo) GetByIDTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.User, error) {
return r.getByID(ctx, tx, id)
}
func (r *UsersRepo) GetByUsername(ctx context.Context, username string) (*dto.User, error) {
const query = `SELECT id, username, name, created_at FROM users WHERE username = $1`
return scanUser(r.pool.QueryRow(ctx, query, username))
}
func (r *UsersRepo) GetCredentialsByUsername(ctx context.Context, username string) (*dto.UserCredentials, error) {
const query = `SELECT id, username, name, created_at, password_hash FROM users WHERE username = $1`
var credentials dto.UserCredentials
err := r.pool.QueryRow(ctx, query, username).Scan(
&credentials.User.ID,
&credentials.User.Username,
&credentials.User.DisplayName,
&credentials.User.CreatedAt,
&credentials.PasswordHash,
)
if err != nil {
return nil, apperr.WrapPostgres(err, "failed to get user credentials")
}
return &credentials, nil
}
func (r *UsersRepo) Delete(ctx context.Context, id uuid.UUID) error {
const query = `DELETE FROM users WHERE id = $1`
ct, err := r.pool.Exec(ctx, query, id)
if err != nil {
return apperr.WrapPostgres(err, "failed to delete user")
}
if ct.RowsAffected() == 0 {
return apperr.New(apperr.CodeNotFound, "user not found")
}
return nil
}
func (r *UsersRepo) create(ctx context.Context, conn postgres.Conn, req dto.CreateStoredUser) error {
const query = `INSERT INTO users (id, username, name, password_hash, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6)`
_, err := conn.Exec(ctx, query, req.ID, req.Username, req.DisplayName, req.PasswordHash, req.CreatedAt, req.UpdatedAt)
if err != nil {
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
pgErr.Code == pgerrcode.UniqueViolation && pgErr.ConstraintName == "users_username_unique" {
return apperr.Wrap(err, apperr.CodeConflict, "username already exists")
}
return apperr.WrapPostgres(err, "failed to create user")
}
return nil
}
func (r *UsersRepo) getByID(ctx context.Context, conn postgres.Conn, id uuid.UUID) (*dto.User, error) {
const query = `SELECT id, username, name, created_at FROM users WHERE id = $1`
return scanUser(conn.QueryRow(ctx, query, id))
}
func scanUser(row pgx.Row) (*dto.User, error) {
var user dto.User
if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt); err != nil {
return nil, apperr.WrapPostgres(err, "failed to get user")
}
return &user, nil
}