forked from mtusi2026/mtusi2026lab2
Реализация на 4
This commit is contained in:
@@ -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)
|
||||
}
|
||||
@@ -2,157 +2,250 @@ package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
inmemory2 "gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory"
|
||||
"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 {
|
||||
*BaseHandler
|
||||
users inmemory2.UserCache
|
||||
chats inmemory2.ChatCache
|
||||
messages inmemory2.MessageCache
|
||||
router router.Router
|
||||
provider jwtprovider.Provider
|
||||
validator *validator.ValidatorImpl
|
||||
|
||||
chat chat.API
|
||||
}
|
||||
|
||||
func NewChatHandler(base *BaseHandler, users inmemory2.UserCache, chats inmemory2.ChatCache, messages inmemory2.MessageCache) Handler {
|
||||
return &ChatHandler{BaseHandler: base, users: users, chats: chats, messages: messages}
|
||||
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.Post("/api/v1/chats", h.Create)
|
||||
h.router.Get("/api/v1/chats", h.Get)
|
||||
h.router.Get("/api/v1/chats/{chat_id}", h.GetByID)
|
||||
h.router.Post("/api/v1/chats/{chat_id}/messages", h.SendMessage)
|
||||
h.router.Get("/api/v1/chats/{chat_id}/messages", h.GetMessages)
|
||||
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()
|
||||
user, ok := h.authenticatedUser(w, r, h.users)
|
||||
if !ok {
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
var req contracts.CreateChat
|
||||
if !h.Decode(w, r, &req) || !h.Validate(w, r, &req) {
|
||||
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
|
||||
return
|
||||
}
|
||||
chat, err := h.chats.Create(ctx, dto.CreateChat{
|
||||
CreatorID: user.ID,
|
||||
|
||||
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 {
|
||||
h.JSONError(ctx, w, err)
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
h.JSONResponse(w, http.StatusCreated, contractChat(chat))
|
||||
|
||||
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()
|
||||
user, ok := h.authenticatedUser(w, r, h.users)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, afterID, ok := h.pageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, err := h.chats.ListForMember(ctx, user.ID, limit, afterID)
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, err)
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
items := make([]contracts.Chat, 0, len(page.Items))
|
||||
for _, chat := range page.Items {
|
||||
items = append(items, contractChat(chat))
|
||||
|
||||
limit, afterID, ok := framework.PageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.JSONResponse(w, http.StatusOK, contracts.ChatPage{Items: items, NextCursor: cursorString(page.NextCursorID)})
|
||||
|
||||
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()
|
||||
user, ok := h.authenticatedUser(w, r, h.users)
|
||||
if !ok {
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
chatID, err := h.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
|
||||
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
chat, err := h.chats.GetForMember(ctx, chatID, user.ID)
|
||||
|
||||
resp, err := h.chat.GetForMember(ctx, dto.ChatMember{
|
||||
UserID: userData.UserID,
|
||||
ChatID: chatID,
|
||||
})
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, err)
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
h.JSONResponse(w, http.StatusOK, contractChat(chat))
|
||||
|
||||
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()
|
||||
user, ok := h.authenticatedUser(w, r, h.users)
|
||||
if !ok {
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
chatID, err := h.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
|
||||
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if _, err := h.chats.GetForMember(ctx, chatID, user.ID); err != nil {
|
||||
h.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
var req contracts.CreateMessage
|
||||
if !h.Decode(w, r, &req) || !h.Validate(w, r, &req) {
|
||||
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
|
||||
return
|
||||
}
|
||||
message, err := h.messages.Create(ctx, dto.CreateMessage{ChatID: chatID, SenderID: user.ID, Text: req.Text})
|
||||
|
||||
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 {
|
||||
h.JSONError(ctx, w, err)
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
h.JSONResponse(w, http.StatusCreated, contractMessage(message))
|
||||
|
||||
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()
|
||||
user, ok := h.authenticatedUser(w, r, h.users)
|
||||
if !ok {
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
chatID, err := h.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
|
||||
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if _, err := h.chats.GetForMember(ctx, chatID, user.ID); err != nil {
|
||||
h.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
limit, afterID, ok := h.pageParams(w, r)
|
||||
|
||||
limit, afterID, ok := framework.PageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, err := h.messages.ListForChat(ctx, chatID, user.ID, limit, afterID)
|
||||
|
||||
page, err := h.chat.ListForChat(ctx, dto.MessageFilters{
|
||||
ChatID: chatID,
|
||||
UserID: userData.UserID,
|
||||
Limit: limit,
|
||||
AfterID: afterID,
|
||||
})
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, err)
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]contracts.Message, 0, len(page.Items))
|
||||
for _, message := range page.Items {
|
||||
items = append(items, contractMessage(message))
|
||||
items = append(items, contracts.Message{
|
||||
Id: message.ID,
|
||||
ChatId: message.ChatID,
|
||||
SenderId: message.SenderID,
|
||||
Text: message.Text,
|
||||
CreatedAt: message.CreatedAt,
|
||||
})
|
||||
}
|
||||
h.JSONResponse(w, http.StatusOK, contracts.MessagePage{Items: items, NextCursor: cursorString(page.NextCursorID)})
|
||||
}
|
||||
|
||||
func contractChat(chat dto.Chat) contracts.Chat {
|
||||
return contracts.Chat{Id: chat.ID, Title: chat.Title, MemberIds: chat.MemberIDs, CreatedAt: chat.CreatedAt}
|
||||
}
|
||||
|
||||
func contractMessage(message dto.Message) contracts.Message {
|
||||
return 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 {
|
||||
@@ -162,3 +255,7 @@ func cursorString(id *uuid.UUID) *string {
|
||||
value := id.String()
|
||||
return &value
|
||||
}
|
||||
|
||||
func validText(value string, maxLength int) bool {
|
||||
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxLength
|
||||
}
|
||||
|
||||
@@ -8,9 +8,8 @@ import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
)
|
||||
|
||||
type Server interface {
|
||||
@@ -26,16 +25,16 @@ type server struct {
|
||||
ready atomic.Bool
|
||||
}
|
||||
|
||||
func New(cfg *config.Server, router chi.Router) Server {
|
||||
func New(cfg *config.Config, router router.Router) Server {
|
||||
s := server{
|
||||
server: http.Server{
|
||||
Addr: cfg.BindAddress(),
|
||||
Addr: cfg.Server.BindAddress(),
|
||||
Handler: router,
|
||||
ReadTimeout: cfg.ReadTimeout,
|
||||
WriteTimeout: cfg.WriteTimeout,
|
||||
IdleTimeout: cfg.IdleTimeout,
|
||||
ReadTimeout: cfg.Server.ReadTimeout,
|
||||
WriteTimeout: cfg.Server.WriteTimeout,
|
||||
IdleTimeout: cfg.Server.IdleTimeout,
|
||||
},
|
||||
cfg: cfg,
|
||||
cfg: cfg.Server,
|
||||
ready: atomic.Bool{},
|
||||
}
|
||||
|
||||
|
||||
@@ -1,220 +1,5 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
v10 "github.com/go-playground/validator/v10"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory"
|
||||
"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/validator"
|
||||
)
|
||||
|
||||
const (
|
||||
HeaderContentType = "Content-Type"
|
||||
HeaderRequestID = "X-Request-Id"
|
||||
HeaderUserID = "X-User-Id"
|
||||
)
|
||||
|
||||
type Handler interface {
|
||||
RegisterRoutes()
|
||||
}
|
||||
|
||||
type BaseHandler struct {
|
||||
router chi.Router
|
||||
validator *validator.ValidatorImpl
|
||||
}
|
||||
|
||||
func NewBaseHandler(r chi.Router) *BaseHandler {
|
||||
return &BaseHandler{
|
||||
router: r,
|
||||
validator: validator.NewValidatorImpl(),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *BaseHandler) validate(ctx context.Context, value any) error {
|
||||
err := h.validator.ValidateCtx(ctx, value)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var fieldErrors v10.ValidationErrors
|
||||
if errors.As(err, &fieldErrors) {
|
||||
return apperr.Wrap(err, apperr.CodeInvalidRequest, "invalid request fields")
|
||||
}
|
||||
return apperr.Wrap(err, apperr.CodeInternalError, "validation failed")
|
||||
}
|
||||
|
||||
func (h *BaseHandler) Validate(w http.ResponseWriter, r *http.Request, value any) bool {
|
||||
if err := h.validate(r.Context(), value); err != nil {
|
||||
h.JSONError(r.Context(), w, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *BaseHandler) JSONResponse(w http.ResponseWriter, status int, body any) {
|
||||
w.Header().Set(HeaderContentType, "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
if status == http.StatusNoContent {
|
||||
return
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(body); err != nil {
|
||||
wrapped := apperr.Wrap(err, apperr.CodeInternal, "failed json encode")
|
||||
slog.Error("response", "error", wrapped)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *BaseHandler) JSONError(ctx context.Context, w http.ResponseWriter, err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
requestId, ok := ctx.Value(HeaderRequestID).(uuid.UUID)
|
||||
if !ok {
|
||||
requestId = uuid.New()
|
||||
}
|
||||
w.Header().Set(HeaderRequestID, requestId.String())
|
||||
|
||||
appErr, ok := apperr.As(err)
|
||||
if !ok {
|
||||
appErr = apperr.New(apperr.CodeInternalError, "internal server error")
|
||||
}
|
||||
slog.Error("response", "error", err, "status", appErr.Code().HTTPStatus(), "requestId", requestId.String())
|
||||
h.JSONResponse(w, appErr.Code().HTTPStatus(), contracts.Error{
|
||||
Error: struct {
|
||||
Code contracts.ErrorErrorCode `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestId string `json:"request_id"`
|
||||
}{
|
||||
Code: contracts.ErrorErrorCode(appErr.Code()),
|
||||
Message: apperr.PublicMessage(appErr),
|
||||
RequestId: requestId.String(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *BaseHandler) Decode(w http.ResponseWriter, r *http.Request, object any) bool {
|
||||
mediaType, params, err := mime.ParseMediaType(r.Header.Get(HeaderContentType))
|
||||
if err != nil || mediaType != "application/json" ||
|
||||
(params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeUnsupportedMediaType, "expected application/json"))
|
||||
return false
|
||||
}
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(object); err != nil {
|
||||
h.JSONError(r.Context(), w, apperr.Wrap(err, apperr.CodeBadRequest, "failed decode"))
|
||||
return false
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); err != io.EOF {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "expected one JSON object"))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *BaseHandler) PathParam(r *http.Request, key string) string {
|
||||
return chi.URLParam(r, key)
|
||||
}
|
||||
|
||||
func (h *BaseHandler) QueryParam(r *http.Request, key string) string {
|
||||
return r.URL.Query().Get(key)
|
||||
}
|
||||
|
||||
func (h *BaseHandler) HeaderParam(r *http.Request, key string) string {
|
||||
return r.Header.Get(key)
|
||||
}
|
||||
|
||||
func (h *BaseHandler) ParseIDFromPathParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := h.PathParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (h *BaseHandler) ParseIDFromQueryParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := h.QueryParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (h *BaseHandler) ParseIDFromHeaderParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := h.HeaderParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "missing or invalid user ID"))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (h *BaseHandler) authenticatedUser(w http.ResponseWriter, r *http.Request, users inmemory.UserCache) (dto.User, bool) {
|
||||
id, err := h.ParseIDFromHeaderParam(r.Context(), w, r, HeaderUserID)
|
||||
if err != nil {
|
||||
return dto.User{}, false
|
||||
}
|
||||
user, err := users.GetByID(r.Context(), id)
|
||||
if err != nil {
|
||||
if appErr, ok := apperr.As(err); ok && appErr.Code() == apperr.CodeNotFound {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeUnauthorized, "unknown user ID"))
|
||||
} else {
|
||||
h.JSONError(r.Context(), w, err)
|
||||
}
|
||||
return dto.User{}, false
|
||||
}
|
||||
return user, true
|
||||
}
|
||||
|
||||
func (h *BaseHandler) pageParams(w http.ResponseWriter, r *http.Request) (*int, *uuid.UUID, bool) {
|
||||
query := r.URL.Query()
|
||||
var limit *int
|
||||
if values, exists := query["limit"]; exists {
|
||||
if len(values) != 1 {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid limit"))
|
||||
return nil, nil, false
|
||||
}
|
||||
value, err := strconv.Atoi(values[0])
|
||||
if err != nil || value < 1 || value > 100 {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid limit"))
|
||||
return nil, nil, false
|
||||
}
|
||||
limit = &value
|
||||
}
|
||||
var afterID *uuid.UUID
|
||||
if values, exists := query["cursor"]; exists {
|
||||
if len(values) != 1 {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid cursor"))
|
||||
return nil, nil, false
|
||||
}
|
||||
id, err := uuid.Parse(values[0])
|
||||
if err != nil || id == uuid.Nil {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid cursor"))
|
||||
return nil, nil, false
|
||||
}
|
||||
afterID = &id
|
||||
}
|
||||
return limit, afterID, true
|
||||
}
|
||||
|
||||
@@ -5,33 +5,35 @@ import (
|
||||
|
||||
"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 HealthHandler struct {
|
||||
*BaseHandler
|
||||
router router.Router
|
||||
server Server
|
||||
}
|
||||
|
||||
func NewHealthHandler(base *BaseHandler, server Server) Handler {
|
||||
func NewHealthHandler(r router.Router, server Server) Handler {
|
||||
return &HealthHandler{
|
||||
BaseHandler: base,
|
||||
server: server,
|
||||
router: r,
|
||||
server: server,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) RegisterRoutes() {
|
||||
h.router.Get("/health/ready", h.Ready)
|
||||
h.router.Get("/health/live", h.Live)
|
||||
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) {
|
||||
h.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.server.Ready() {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "server is not ready"))
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "server is not ready"))
|
||||
return
|
||||
}
|
||||
h.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
|
||||
}
|
||||
|
||||
@@ -1,50 +1 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func NewRouter() chi.Router {
|
||||
r := chi.NewRouter()
|
||||
r.Use(requestIdMiddleware, loggingMiddleware)
|
||||
return r
|
||||
}
|
||||
|
||||
func requestIdMiddleware(next http.Handler) http.Handler {
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
requestID := uuid.New()
|
||||
w.Header().Set(HeaderRequestID, requestID.String())
|
||||
ctx = context.WithValue(ctx, HeaderRequestID, requestID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
}
|
||||
return http.HandlerFunc(fn)
|
||||
}
|
||||
|
||||
func loggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
started := time.Now()
|
||||
wrapped := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
next.ServeHTTP(wrapped, r)
|
||||
|
||||
status := wrapped.Status()
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
slog.InfoContext(r.Context(), "http request",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", status,
|
||||
"duration", time.Since(started),
|
||||
"bytes", wrapped.BytesWritten(),
|
||||
"request_id", w.Header().Get(HeaderRequestID),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,64 +3,87 @@ package http
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"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 {
|
||||
*BaseHandler
|
||||
router router.Router
|
||||
provider jwtprovider.Provider
|
||||
validator *validator.ValidatorImpl
|
||||
|
||||
users inmemory.UserCache
|
||||
user user.API
|
||||
}
|
||||
|
||||
func NewUserHandler(base *BaseHandler, users inmemory.UserCache) Handler {
|
||||
func NewUserHandler(r router.Router, provider jwtprovider.Provider, v *validator.ValidatorImpl, api user.API) Handler {
|
||||
return &UserHandler{
|
||||
BaseHandler: base,
|
||||
users: users,
|
||||
router: r,
|
||||
provider: provider,
|
||||
validator: v,
|
||||
user: api,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *UserHandler) RegisterRoutes() {
|
||||
h.router.Post("/api/v1/users", h.Create)
|
||||
h.router.Get("/api/v1/users/me", h.GetMe)
|
||||
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 !h.Decode(w, r, &req) || !h.Validate(w, r, &req) {
|
||||
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.users.Create(ctx, dto.CreateUser{
|
||||
toCreate := dto.CreateUser{
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
})
|
||||
}
|
||||
|
||||
if req.Password != nil {
|
||||
toCreate.Password = *req.Password
|
||||
}
|
||||
|
||||
resp, err := h.user.Create(ctx, toCreate)
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, err)
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
h.JSONResponse(w, http.StatusCreated, contracts.User{
|
||||
CreatedAt: user.CreatedAt,
|
||||
DisplayName: user.DisplayName,
|
||||
Id: user.ID,
|
||||
Username: user.Username,
|
||||
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) {
|
||||
user, ok := h.authenticatedUser(w, r, h.users)
|
||||
if !ok {
|
||||
ctx := r.Context()
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
h.JSONResponse(w, http.StatusOK, contracts.User{
|
||||
CreatedAt: user.CreatedAt,
|
||||
DisplayName: user.DisplayName,
|
||||
Id: user.ID,
|
||||
Username: user.Username,
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
package inmemory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
const chatCacheName = "CHATS_CACHE"
|
||||
|
||||
type ChatCache interface {
|
||||
Create(ctx context.Context, input dto.CreateChat) (dto.Chat, error)
|
||||
GetForMember(ctx context.Context, chatID, userID uuid.UUID) (dto.Chat, error)
|
||||
ListForMember(ctx context.Context, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Chat], error)
|
||||
}
|
||||
|
||||
type chatCache struct {
|
||||
mu sync.RWMutex
|
||||
store *CopyAndWriteCache[uuid.UUID, dto.Chat]
|
||||
users UserCache
|
||||
}
|
||||
|
||||
func NewChatCache(users UserCache) ChatCache {
|
||||
if users == nil {
|
||||
panic("chat cache requires a user repository")
|
||||
}
|
||||
return &chatCache{
|
||||
store: NewCopyAndWriteCache[uuid.UUID, dto.Chat](chatCacheName),
|
||||
users: users,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *chatCache) Create(ctx context.Context, input dto.CreateChat) (dto.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Chat{}, err
|
||||
}
|
||||
if strings.TrimSpace(input.Title) == "" || utf8.RuneCountInString(input.Title) > 100 ||
|
||||
len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "invalid chat fields")
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(input.MemberIDs))
|
||||
for _, memberID := range input.MemberIDs {
|
||||
if memberID == uuid.Nil {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "invalid chat member")
|
||||
}
|
||||
if _, duplicate := seen[memberID]; duplicate {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "duplicate chat member")
|
||||
}
|
||||
seen[memberID] = struct{}{}
|
||||
if _, err := c.users.GetByID(ctx, memberID); err != nil {
|
||||
if appErr, ok := apperr.As(err); ok && appErr.Code() == apperr.CodeNotFound {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "unknown chat member")
|
||||
}
|
||||
return dto.Chat{}, err
|
||||
}
|
||||
}
|
||||
if _, included := seen[input.CreatorID]; !included {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "creator must be a chat member")
|
||||
}
|
||||
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return dto.Chat{}, apperr.Wrap(err, apperr.CodeInternalError, "generate chat ID")
|
||||
}
|
||||
chat := dto.Chat{
|
||||
ID: id,
|
||||
Title: input.Title,
|
||||
MemberIDs: append([]uuid.UUID(nil), input.MemberIDs...),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if !c.store.Store(chat.ID, chat) {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInternalError, "store chat")
|
||||
}
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (c *chatCache) GetForMember(ctx context.Context, chatID, userID uuid.UUID) (dto.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Chat{}, err
|
||||
}
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
chat, ok := c.store.Get(chatID)
|
||||
if !ok || !slices.Contains(chat.MemberIDs, userID) {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeNotFound, "chat not found")
|
||||
}
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (c *chatCache) ListForMember(ctx context.Context, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Chat], error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Page[dto.Chat]{}, err
|
||||
}
|
||||
pageSize, err := pageLimit(limit)
|
||||
if err != nil {
|
||||
return dto.Page[dto.Chat]{}, err
|
||||
}
|
||||
|
||||
c.mu.RLock()
|
||||
all := c.store.GetList()
|
||||
chats := make([]dto.Chat, 0, len(all))
|
||||
for _, chat := range all {
|
||||
if slices.Contains(chat.MemberIDs, userID) {
|
||||
chats = append(chats, cloneChat(chat))
|
||||
}
|
||||
}
|
||||
c.mu.RUnlock()
|
||||
|
||||
sort.Slice(chats, func(i, j int) bool {
|
||||
return lessKey(chats[i].CreatedAt, chats[i].ID, chats[j].CreatedAt, chats[j].ID)
|
||||
})
|
||||
start := 0
|
||||
if afterID != nil {
|
||||
start = -1
|
||||
for i, chat := range chats {
|
||||
if chat.ID == *afterID {
|
||||
start = i + 1
|
||||
break
|
||||
}
|
||||
}
|
||||
if start < 0 {
|
||||
return dto.Page[dto.Chat]{}, apperr.New(apperr.CodeInvalidRequest, "invalid cursor")
|
||||
}
|
||||
}
|
||||
end := min(start+pageSize, len(chats))
|
||||
page := dto.Page[dto.Chat]{Items: chats[start:end]}
|
||||
if end < len(chats) {
|
||||
id := chats[end-1].ID
|
||||
page.NextCursorID = &id
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func cloneChat(chat dto.Chat) dto.Chat {
|
||||
chat.MemberIDs = append([]uuid.UUID(nil), chat.MemberIDs...)
|
||||
return chat
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
package inmemory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
const MessageCacheName = "MESSAGE_CACHE"
|
||||
|
||||
type MessageCache interface {
|
||||
Create(ctx context.Context, input dto.CreateMessage) (dto.Message, error)
|
||||
ListForChat(ctx context.Context, chatID, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Message], error)
|
||||
}
|
||||
|
||||
type messageCache struct {
|
||||
mu sync.RWMutex
|
||||
store *CopyAndWriteCache[uuid.UUID, dto.Message]
|
||||
byChat map[uuid.UUID][]dto.Message
|
||||
chats ChatCache
|
||||
}
|
||||
|
||||
func NewMessageCache(chats ChatCache) MessageCache {
|
||||
if chats == nil {
|
||||
panic("message cache requires a chat repository")
|
||||
}
|
||||
return &messageCache{
|
||||
store: NewCopyAndWriteCache[uuid.UUID, dto.Message](MessageCacheName),
|
||||
byChat: make(map[uuid.UUID][]dto.Message),
|
||||
chats: chats,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *messageCache) Create(ctx context.Context, input dto.CreateMessage) (dto.Message, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Message{}, err
|
||||
}
|
||||
if _, err := c.chats.GetForMember(ctx, input.ChatID, input.SenderID); err != nil {
|
||||
return dto.Message{}, err
|
||||
}
|
||||
if strings.TrimSpace(input.Text) == "" || utf8.RuneCountInString(input.Text) > 4000 {
|
||||
return dto.Message{}, apperr.New(apperr.CodeInvalidRequest, "invalid message text")
|
||||
}
|
||||
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return dto.Message{}, apperr.Wrap(err, apperr.CodeInternalError, "generate message ID")
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
message := dto.Message{
|
||||
ID: id,
|
||||
ChatID: input.ChatID,
|
||||
SenderID: input.SenderID,
|
||||
Text: input.Text,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
if !c.store.Store(message.ID, message) {
|
||||
return dto.Message{}, apperr.New(apperr.CodeInternalError, "store message")
|
||||
}
|
||||
messages := c.byChat[message.ChatID]
|
||||
index := sort.Search(len(messages), func(i int) bool {
|
||||
return !lessKey(messages[i].CreatedAt, messages[i].ID, message.CreatedAt, message.ID)
|
||||
})
|
||||
messages = append(messages, dto.Message{})
|
||||
copy(messages[index+1:], messages[index:])
|
||||
messages[index] = message
|
||||
c.byChat[message.ChatID] = messages
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (c *messageCache) ListForChat(ctx context.Context, chatID, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Message], error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Page[dto.Message]{}, err
|
||||
}
|
||||
if _, err := c.chats.GetForMember(ctx, chatID, userID); err != nil {
|
||||
return dto.Page[dto.Message]{}, err
|
||||
}
|
||||
pageSize, err := pageLimit(limit)
|
||||
if err != nil {
|
||||
return dto.Page[dto.Message]{}, err
|
||||
}
|
||||
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
messages := c.byChat[chatID]
|
||||
start := 0
|
||||
if afterID != nil {
|
||||
cursor, ok := c.store.Get(*afterID)
|
||||
if !ok || cursor.ChatID != chatID {
|
||||
return dto.Page[dto.Message]{}, apperr.New(apperr.CodeInvalidRequest, "invalid cursor")
|
||||
}
|
||||
start = sort.Search(len(messages), func(i int) bool {
|
||||
return lessKey(cursor.CreatedAt, cursor.ID, messages[i].CreatedAt, messages[i].ID)
|
||||
})
|
||||
}
|
||||
end := min(start+pageSize, len(messages))
|
||||
items := make([]dto.Message, end-start)
|
||||
copy(items, messages[start:end])
|
||||
page := dto.Page[dto.Message]{Items: items}
|
||||
if end < len(messages) {
|
||||
id := messages[end-1].ID
|
||||
page.NextCursorID = &id
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package inmemory
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
func pageLimit(rawLimit *int) (int, error) {
|
||||
limit := 50
|
||||
if rawLimit != nil {
|
||||
limit = *rawLimit
|
||||
}
|
||||
if limit < 1 || limit > 100 {
|
||||
return 0, apperr.New(apperr.CodeInvalidRequest, "invalid limit")
|
||||
}
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
func lessKey(leftTime time.Time, leftID uuid.UUID, rightTime time.Time, rightID uuid.UUID) bool {
|
||||
if !leftTime.Equal(rightTime) {
|
||||
return leftTime.Before(rightTime)
|
||||
}
|
||||
return bytes.Compare(leftID[:], rightID[:]) < 0
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
package inmemory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
const UserCacheName = "USERS_CACHE"
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type UserCache interface {
|
||||
Create(ctx context.Context, input dto.CreateUser) (dto.User, error)
|
||||
GetByID(ctx context.Context, id uuid.UUID) (dto.User, error)
|
||||
GetByUsername(ctx context.Context, username string) (dto.User, error)
|
||||
}
|
||||
|
||||
type userCache struct {
|
||||
mu sync.RWMutex
|
||||
store *CopyAndWriteCache[uuid.UUID, dto.User]
|
||||
byUsername map[string]uuid.UUID
|
||||
}
|
||||
|
||||
func NewUserCache() UserCache {
|
||||
return &userCache{
|
||||
store: NewCopyAndWriteCache[uuid.UUID, dto.User](UserCacheName),
|
||||
byUsername: make(map[string]uuid.UUID),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *userCache) Create(ctx context.Context, input dto.CreateUser) (dto.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
if !usernamePattern.MatchString(input.Username) ||
|
||||
strings.TrimSpace(input.DisplayName) == "" ||
|
||||
utf8.RuneCountInString(input.DisplayName) > 100 {
|
||||
return dto.User{}, apperr.New(apperr.CodeInvalidRequest, "invalid user fields")
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if _, exists := c.byUsername[input.Username]; exists {
|
||||
return dto.User{}, apperr.New(apperr.CodeConflict, "username already exists")
|
||||
}
|
||||
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return dto.User{}, apperr.Wrap(err, apperr.CodeInternalError, "generate user ID")
|
||||
}
|
||||
user := dto.User{
|
||||
ID: id,
|
||||
Username: input.Username,
|
||||
DisplayName: input.DisplayName,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
if !c.store.Store(user.ID, user) {
|
||||
return dto.User{}, apperr.New(apperr.CodeInternalError, "store user")
|
||||
}
|
||||
c.byUsername[user.Username] = user.ID
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (c *userCache) GetByID(ctx context.Context, id uuid.UUID) (dto.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
user, ok := c.store.Get(id)
|
||||
if !ok {
|
||||
return dto.User{}, apperr.New(apperr.CodeNotFound, "user not found")
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (c *userCache) GetByUsername(ctx context.Context, username string) (dto.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
id, ok := c.byUsername[username]
|
||||
if !ok {
|
||||
return dto.User{}, apperr.New(apperr.CodeNotFound, "user not found")
|
||||
}
|
||||
user, ok := c.store.Get(id)
|
||||
if !ok {
|
||||
return dto.User{}, apperr.New(apperr.CodeInternalError, "user index is inconsistent")
|
||||
}
|
||||
return user, 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
|
||||
}
|
||||
Reference in New Issue
Block a user