lab4 done
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) authorizedChat(c echo.Context, requestedChat domain.Chat) (domain.Chat, bool, error) {
|
||||
chat, err := h.useCase.GetChat(c.Request().Context(), authenticatedUser(c).ID, requestedChat)
|
||||
if err != nil {
|
||||
return domain.Chat{}, false, h.useCaseError(c, err)
|
||||
}
|
||||
return chat, true, nil
|
||||
}
|
||||
|
||||
func (h *Chat) cursorPosition(raw string, present bool, scope, owner string) (*domain.Position, error) {
|
||||
if !present {
|
||||
return nil, nil
|
||||
}
|
||||
if raw == "" {
|
||||
return nil, errors.New("empty cursor")
|
||||
}
|
||||
createdAt, id, err := h.cursor.decode(raw, scope, owner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &domain.Position{CreatedAt: createdAt, ID: id}, nil
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mime"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
func (h *Chat) WithAttachments(service *attachment.Service) *Chat { h.attachments = service; return h }
|
||||
func (h *Chat) uploadAttachment(c echo.Context) error {
|
||||
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: c.Param("chat_id")})
|
||||
if err != nil || !ok {
|
||||
return err
|
||||
}
|
||||
filename, present, err := oneQueryValue(c, "filename")
|
||||
if err != nil || !present {
|
||||
return h.invalid(c, "Требуется один filename")
|
||||
}
|
||||
if c.Request().ContentLength > attachment.MaxBytes {
|
||||
return h.writeError(c, 413, "payload_too_large", "Файл превышает 10 MiB")
|
||||
}
|
||||
// Both socket reads and the application operation have a fixed deadline.
|
||||
deadline := time.Now().Add(attachment.UploadTimeout)
|
||||
_ = http.NewResponseController(c.Response().Writer).SetReadDeadline(deadline)
|
||||
defer http.NewResponseController(c.Response().Writer).SetReadDeadline(time.Time{})
|
||||
c.Request().Body = http.MaxBytesReader(c.Response(), c.Request().Body, attachment.MaxBytes+1)
|
||||
a, err := h.attachments.Upload(c.Request().Context(), chat.ID, authenticatedUser(c).ID, filename, c.Request().Header.Get("Content-Type"), c.Request().Body)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, a)
|
||||
}
|
||||
func (h *Chat) getAttachment(c echo.Context) error {
|
||||
a, err := h.attachments.Get(c.Request().Context(), c.Param("attachment_id"), authenticatedUser(c).ID)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, a)
|
||||
}
|
||||
func (h *Chat) attachmentContent(c echo.Context) error {
|
||||
a, err := h.attachments.Get(c.Request().Context(), c.Param("attachment_id"), authenticatedUser(c).ID)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
variant, present, err := oneQueryValue(c, "variant")
|
||||
if err != nil {
|
||||
return h.invalid(c, "Некорректный variant")
|
||||
}
|
||||
if present && variant != "original" {
|
||||
return h.writeError(c, 404, "not_found", "Вариант не найден")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(c.Request().Context(), 45*time.Second)
|
||||
defer cancel()
|
||||
obj, err := h.attachments.Content(ctx, a)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
defer obj.Close()
|
||||
c.Response().Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": a.Filename}))
|
||||
c.Response().Header().Set("X-Content-Type-Options", "nosniff")
|
||||
c.Response().Header().Set("Cache-Control", "private, no-store")
|
||||
return c.Stream(http.StatusOK, a.ContentType, obj)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) createChat(c echo.Context) error {
|
||||
var request dto.CreateChatRequest
|
||||
if err := decodeJSON(c, &request); err != nil {
|
||||
return h.jsonError(c, err)
|
||||
}
|
||||
callerID := authenticatedUser(c).ID
|
||||
chat, err := h.useCase.CreateChat(c.Request().Context(), callerID, createChatRequestToDomain(request))
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, createChatResponseFromDomain(chat))
|
||||
}
|
||||
|
||||
func createChatRequestToDomain(request dto.CreateChatRequest) domain.Chat {
|
||||
return domain.Chat{Title: request.Title, MemberIDs: request.MemberIDs}
|
||||
}
|
||||
|
||||
func createChatResponseFromDomain(chat domain.Chat) dto.CreateChatResponse {
|
||||
return dto.CreateChatResponse{
|
||||
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (h *Chat) createMessage(c echo.Context) error {
|
||||
request := dto.CreateMessageRequest{ChatID: c.Param("chat_id")}
|
||||
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: request.ChatID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if err := decodeJSON(c, &request); err != nil {
|
||||
return h.jsonError(c, err)
|
||||
}
|
||||
request.ChatID = chat.ID
|
||||
|
||||
keys := c.Request().Header.Values("Idempotency-Key")
|
||||
if len(keys) != 1 || !idempotencyKeyPattern.MatchString(keys[0]) {
|
||||
return h.invalid(c, "Требуется Idempotency-Key: ASCII [A-Za-z0-9._:-]{1,128}")
|
||||
}
|
||||
input := createMessageRequestToDomain(request)
|
||||
input.IdempotencyKey = keys[0]
|
||||
message, err := h.useCase.CreateMessage(c.Request().Context(), authenticatedUser(c).ID, input)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, createMessageResponseFromDomain(message))
|
||||
}
|
||||
|
||||
func createMessageRequestToDomain(request dto.CreateMessageRequest) domain.Message {
|
||||
return domain.Message{ChatID: request.ChatID, Text: request.Text, AttachmentIDs: request.AttachmentIDs}
|
||||
}
|
||||
|
||||
func createMessageResponseFromDomain(message domain.Message) dto.CreateMessageResponse {
|
||||
return dto.CreateMessageResponse{
|
||||
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
|
||||
Text: message.Text, AttachmentIDs: nonnilIDs(message.AttachmentIDs), CreatedAt: dto.Timestamp(message.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func nonnilIDs(ids []string) []string {
|
||||
if ids == nil {
|
||||
return []string{}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) createUser(c echo.Context) error {
|
||||
var request dto.CreateUserRequest
|
||||
if err := decodeJSON(c, &request); err != nil {
|
||||
return h.jsonError(c, err)
|
||||
}
|
||||
user, err := h.useCase.CreateUser(c.Request().Context(), createUserRequestToDomain(request), request.Password)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, createUserResponseFromDomain(user))
|
||||
}
|
||||
|
||||
func createUserRequestToDomain(request dto.CreateUserRequest) domain.User {
|
||||
return domain.User{Username: request.Username, DisplayName: request.DisplayName}
|
||||
}
|
||||
|
||||
func createUserResponseFromDomain(user domain.User) dto.CreateUserResponse {
|
||||
return dto.CreateUserResponse{
|
||||
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: dto.Timestamp(user.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) currentUser(c echo.Context) error {
|
||||
user := authenticatedUser(c)
|
||||
return c.JSON(http.StatusOK, currentUserResponseFromDomain(user))
|
||||
}
|
||||
|
||||
func currentUserResponseFromDomain(user domain.User) dto.CurrentUserResponse {
|
||||
return dto.CurrentUserResponse{
|
||||
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: dto.Timestamp(user.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type cursorPayload struct {
|
||||
Scope string `json:"scope"`
|
||||
Owner string `json:"owner"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
type cursorCodec struct {
|
||||
secret [32]byte
|
||||
}
|
||||
|
||||
func (c cursorCodec) encode(scope, owner string, createdAt time.Time, id string) string {
|
||||
payload, err := json.Marshal(cursorPayload{
|
||||
Scope: scope,
|
||||
Owner: owner,
|
||||
CreatedAt: createdAt.UTC().Format(time.RFC3339Nano),
|
||||
ID: id,
|
||||
})
|
||||
if err != nil {
|
||||
panic("cannot encode cursor: " + err.Error())
|
||||
}
|
||||
signature := c.sign(payload)
|
||||
return base64.RawURLEncoding.EncodeToString(payload) + "." + base64.RawURLEncoding.EncodeToString(signature)
|
||||
}
|
||||
|
||||
func (c cursorCodec) decode(raw, scope, owner string) (time.Time, string, error) {
|
||||
parts := strings.Split(raw, ".")
|
||||
if len(parts) != 2 {
|
||||
return time.Time{}, "", errors.New("malformed cursor")
|
||||
}
|
||||
payload, err := base64.RawURLEncoding.DecodeString(parts[0])
|
||||
if err != nil {
|
||||
return time.Time{}, "", errors.New("malformed cursor")
|
||||
}
|
||||
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil || !hmac.Equal(signature, c.sign(payload)) {
|
||||
return time.Time{}, "", errors.New("invalid cursor signature")
|
||||
}
|
||||
var value cursorPayload
|
||||
if err := json.Unmarshal(payload, &value); err != nil {
|
||||
return time.Time{}, "", errors.New("malformed cursor payload")
|
||||
}
|
||||
if value.Scope != scope || value.Owner != owner {
|
||||
return time.Time{}, "", errors.New("cursor belongs to another resource")
|
||||
}
|
||||
parsedID, err := uuid.Parse(value.ID)
|
||||
if err != nil || parsedID.String() != value.ID {
|
||||
return time.Time{}, "", errors.New("malformed cursor id")
|
||||
}
|
||||
createdAt, err := time.Parse(time.RFC3339Nano, value.CreatedAt)
|
||||
if err != nil {
|
||||
return time.Time{}, "", errors.New("malformed cursor timestamp")
|
||||
}
|
||||
return createdAt, value.ID, nil
|
||||
}
|
||||
|
||||
func (c cursorCodec) sign(payload []byte) []byte {
|
||||
mac := hmac.New(sha256.New, c.secret[:])
|
||||
_, _ = mac.Write(payload)
|
||||
return mac.Sum(nil)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) invalid(c echo.Context, message string) error {
|
||||
return h.writeError(c, http.StatusBadRequest, "invalid_request", message)
|
||||
}
|
||||
|
||||
func (h *Chat) jsonError(c echo.Context, err error) error {
|
||||
if errors.Is(err, errUnsupportedMediaType) {
|
||||
return h.writeError(c, http.StatusUnsupportedMediaType, "unsupported_media_type", "Content-Type должен быть application/json")
|
||||
}
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
return h.writeError(c, http.StatusRequestEntityTooLarge, "payload_too_large", "Тело запроса слишком большое")
|
||||
}
|
||||
return h.invalid(c, err.Error())
|
||||
}
|
||||
|
||||
func (h *Chat) useCaseError(c echo.Context, err error) error {
|
||||
applicationError, ok := domain.AsApplicationError(err)
|
||||
if !ok {
|
||||
return err
|
||||
}
|
||||
status := http.StatusInternalServerError
|
||||
switch applicationError.Code {
|
||||
case "unsupported_media_type":
|
||||
status = http.StatusUnsupportedMediaType
|
||||
case "payload_too_large":
|
||||
status = http.StatusRequestEntityTooLarge
|
||||
case domain.ErrorUnavailable:
|
||||
status = http.StatusServiceUnavailable
|
||||
case domain.ErrorInvalid:
|
||||
status = http.StatusBadRequest
|
||||
case domain.ErrorUnauthorized:
|
||||
status = http.StatusUnauthorized
|
||||
challenge := `Bearer realm="messenger"`
|
||||
if c.Path() == "/api/v1/auth/sessions" {
|
||||
challenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
}
|
||||
c.Response().Header().Set("WWW-Authenticate", challenge)
|
||||
case domain.ErrorNotFound:
|
||||
status = http.StatusNotFound
|
||||
case domain.ErrorConflict:
|
||||
status = http.StatusConflict
|
||||
}
|
||||
return h.writeError(c, status, string(applicationError.Code), applicationError.Message)
|
||||
}
|
||||
|
||||
func (h *Chat) writeError(c echo.Context, status int, code, message string) error {
|
||||
return c.JSON(status, dto.ErrorResponse{Error: dto.ErrorDetails{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestID(c),
|
||||
}})
|
||||
}
|
||||
|
||||
func (h *Chat) httpErrorHandler(err error, c echo.Context) {
|
||||
if c.Response().Committed {
|
||||
return
|
||||
}
|
||||
status := http.StatusInternalServerError
|
||||
code := "internal_error"
|
||||
message := "Внутренняя ошибка сервера"
|
||||
var httpError *echo.HTTPError
|
||||
if errors.As(err, &httpError) {
|
||||
status = httpError.Code
|
||||
switch status {
|
||||
case http.StatusNotFound:
|
||||
code, message = "not_found", "Объект не найден"
|
||||
case http.StatusMethodNotAllowed, http.StatusBadRequest:
|
||||
code, message = "invalid_request", "Некорректный запрос"
|
||||
}
|
||||
}
|
||||
_ = h.writeError(c, status, code, message)
|
||||
}
|
||||
|
||||
func requestID(c echo.Context) string {
|
||||
value, _ := c.Get(requestIDKey).(string)
|
||||
if value == "" {
|
||||
value = uuid.NewString()
|
||||
c.Set(requestIDKey, value)
|
||||
c.Response().Header().Set("X-Request-Id", value)
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) getChat(c echo.Context) error {
|
||||
request := dto.GetChatRequest{ChatID: c.Param("chat_id")}
|
||||
chat, ok, err := h.authorizedChat(c, getChatRequestToDomain(request))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return c.JSON(http.StatusOK, getChatResponseFromDomain(chat))
|
||||
}
|
||||
|
||||
func getChatRequestToDomain(request dto.GetChatRequest) domain.Chat {
|
||||
return domain.Chat{ID: request.ChatID}
|
||||
}
|
||||
|
||||
func getChatResponseFromDomain(chat domain.Chat) dto.GetChatResponse {
|
||||
return dto.GetChatResponse{
|
||||
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) listChats(c echo.Context) error {
|
||||
limit, err := parseLimit(c)
|
||||
if err != nil {
|
||||
return h.invalid(c, err.Error())
|
||||
}
|
||||
rawCursor, cursorPresent, err := oneQueryValue(c, "cursor")
|
||||
if err != nil {
|
||||
return h.invalid(c, "cursor должен быть указан один раз")
|
||||
}
|
||||
request := dto.ListChatsRequest{Limit: limit, Cursor: rawCursor}
|
||||
userID := authenticatedUser(c).ID
|
||||
position, err := h.cursorPosition(request.Cursor, cursorPresent, "chats", userID)
|
||||
if err != nil {
|
||||
return h.invalid(c, "Некорректный cursor")
|
||||
}
|
||||
|
||||
page, err := h.useCase.ListChats(c.Request().Context(), userID, listChatsRequestToDomain(request, position))
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
var next *string
|
||||
if page.HasMore {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
encoded := h.cursor.encode("chats", userID, last.CreatedAt, last.ID)
|
||||
next = &encoded
|
||||
}
|
||||
return c.JSON(http.StatusOK, listChatsResponseFromDomain(page, next))
|
||||
}
|
||||
|
||||
func listChatsRequestToDomain(request dto.ListChatsRequest, position *domain.Position) domain.Pagination {
|
||||
return domain.Pagination{After: position, Limit: request.Limit}
|
||||
}
|
||||
|
||||
func listChatsResponseFromDomain(page domain.ChatPage, nextCursor *string) dto.ListChatsResponse {
|
||||
items := make([]dto.ListChatsItem, 0, len(page.Items))
|
||||
for _, chat := range page.Items {
|
||||
items = append(items, dto.ListChatsItem{
|
||||
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
|
||||
})
|
||||
}
|
||||
return dto.ListChatsResponse{Items: items, NextCursor: nextCursor}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) listMessages(c echo.Context) error {
|
||||
request := dto.ListMessagesRequest{ChatID: c.Param("chat_id")}
|
||||
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: request.ChatID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
limit, err := parseLimit(c)
|
||||
if err != nil {
|
||||
return h.invalid(c, err.Error())
|
||||
}
|
||||
rawCursor, cursorPresent, err := oneQueryValue(c, "cursor")
|
||||
if err != nil {
|
||||
return h.invalid(c, "cursor должен быть указан один раз")
|
||||
}
|
||||
request.ChatID = chat.ID
|
||||
request.Limit = limit
|
||||
request.Cursor = rawCursor
|
||||
position, err := h.cursorPosition(request.Cursor, cursorPresent, "messages", request.ChatID)
|
||||
if err != nil {
|
||||
return h.invalid(c, "Некорректный cursor")
|
||||
}
|
||||
|
||||
page, err := h.useCase.ListMessages(
|
||||
c.Request().Context(), authenticatedUser(c).ID,
|
||||
listMessagesChatToDomain(request), listMessagesPaginationToDomain(request, position),
|
||||
)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
var next *string
|
||||
if page.HasMore {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
encoded := h.cursor.encode("messages", request.ChatID, last.CreatedAt, last.ID)
|
||||
next = &encoded
|
||||
}
|
||||
return c.JSON(http.StatusOK, listMessagesResponseFromDomain(page, next))
|
||||
}
|
||||
|
||||
func listMessagesChatToDomain(request dto.ListMessagesRequest) domain.Chat {
|
||||
return domain.Chat{ID: request.ChatID}
|
||||
}
|
||||
|
||||
func listMessagesPaginationToDomain(request dto.ListMessagesRequest, position *domain.Position) domain.Pagination {
|
||||
return domain.Pagination{After: position, Limit: request.Limit}
|
||||
}
|
||||
|
||||
func listMessagesResponseFromDomain(page domain.MessagePage, nextCursor *string) dto.ListMessagesResponse {
|
||||
items := make([]dto.ListMessagesItem, 0, len(page.Items))
|
||||
for _, message := range page.Items {
|
||||
items = append(items, dto.ListMessagesItem{
|
||||
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
|
||||
Text: message.Text, AttachmentIDs: nonnilIDs(message.AttachmentIDs), CreatedAt: dto.Timestamp(message.CreatedAt),
|
||||
})
|
||||
}
|
||||
return dto.ListMessagesResponse{Items: items, NextCursor: nextCursor}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
)
|
||||
|
||||
func (h *Chat) liveness(c echo.Context) error {
|
||||
return c.JSON(http.StatusOK, dto.LivenessResponse{Status: "ok"})
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
requestIDKey = "request_id"
|
||||
userKey = "current_user"
|
||||
)
|
||||
|
||||
func (h *Chat) requestIDMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
requestID := uuid.NewString()
|
||||
c.Set(requestIDKey, requestID)
|
||||
c.Response().Header().Set("X-Request-Id", requestID)
|
||||
c.Response().Header().Set("X-Instance-Id", h.instanceID)
|
||||
if h.draining.Load() && c.Request().URL.Path != "/health/live" {
|
||||
return h.writeError(c, http.StatusServiceUnavailable, "unavailable", "Реплика завершает работу")
|
||||
}
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Chat) authenticate(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
user, err := h.useCase.Authenticate(c.Request().Context(), bearerToken(c))
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
c.Set(userKey, user)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
|
||||
func authenticatedUser(c echo.Context) domain.User {
|
||||
return c.Get(userKey).(domain.User)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
)
|
||||
|
||||
func (h *Chat) readiness(c echo.Context) error {
|
||||
ctx, cancel := context.WithTimeout(c.Request().Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := h.useCase.Ready(ctx); err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
if h.attachments != nil {
|
||||
if err := h.attachments.Ready(ctx); err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
}
|
||||
return c.JSON(http.StatusOK, dto.ReadinessResponse{Status: "ok"})
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultLimit = 50
|
||||
maxLimit = 100
|
||||
maxJSONBody = 1 << 20
|
||||
)
|
||||
|
||||
var errUnsupportedMediaType = errors.New("unsupported media type")
|
||||
|
||||
func decodeJSON(c echo.Context, target any) error {
|
||||
mediaType, _, err := mime.ParseMediaType(c.Request().Header.Get(echo.HeaderContentType))
|
||||
if err != nil || mediaType != echo.MIMEApplicationJSON {
|
||||
return errUnsupportedMediaType
|
||||
}
|
||||
reader := http.MaxBytesReader(c.Response(), c.Request().Body, maxJSONBody)
|
||||
decoder := json.NewDecoder(reader)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
return err
|
||||
}
|
||||
return errors.New("Некорректное JSON-тело")
|
||||
}
|
||||
var extra any
|
||||
err = decoder.Decode(&extra)
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
return err
|
||||
}
|
||||
if !errors.Is(err, io.EOF) {
|
||||
return errors.New("JSON-тело должно содержать ровно один объект")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseLimit(c echo.Context) (int, error) {
|
||||
raw, present, err := oneQueryValue(c, "limit")
|
||||
if err != nil {
|
||||
return 0, errors.New("limit должен быть указан один раз")
|
||||
}
|
||||
if !present {
|
||||
return defaultLimit, nil
|
||||
}
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return 0, fmt.Errorf("limit должен быть целым числом от 1 до %d", maxLimit)
|
||||
}
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
func oneQueryValue(c echo.Context, name string) (string, bool, error) {
|
||||
values, present := c.QueryParams()[name]
|
||||
if !present {
|
||||
return "", false, nil
|
||||
}
|
||||
if len(values) != 1 {
|
||||
return "", true, errors.New("query parameter must occur once")
|
||||
}
|
||||
return values[0], true, nil
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
|
||||
"log"
|
||||
"os"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v4/middleware"
|
||||
"github.com/swaggest/swgui/v5emb"
|
||||
)
|
||||
|
||||
// Chat is the HTTP handler and depends only on the application boundary.
|
||||
type Chat struct {
|
||||
attachments *attachment.Service
|
||||
instanceID string
|
||||
draining atomic.Bool
|
||||
useCase UseCase
|
||||
cursor cursorCodec
|
||||
}
|
||||
|
||||
func NewChat(useCase UseCase, cursorKey [32]byte) *Chat {
|
||||
instanceID := os.Getenv("INSTANCE_ID")
|
||||
if instanceID == "" {
|
||||
instanceID = uuid.NewString()
|
||||
}
|
||||
return &Chat{useCase: useCase, cursor: cursorCodec{secret: cursorKey}, instanceID: instanceID}
|
||||
}
|
||||
|
||||
func (h *Chat) Drain() { h.draining.Store(true) }
|
||||
|
||||
func (h *Chat) Router() *echo.Echo {
|
||||
e := echo.New()
|
||||
e.HideBanner = true
|
||||
e.HidePort = true
|
||||
e.HTTPErrorHandler = h.httpErrorHandler
|
||||
e.Use(h.requestIDMiddleware)
|
||||
e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
|
||||
HandleError: true,
|
||||
LogLatency: true,
|
||||
LogMethod: true,
|
||||
LogRoutePath: true,
|
||||
LogURIPath: true,
|
||||
LogRequestID: true,
|
||||
LogStatus: true,
|
||||
LogResponseSize: true,
|
||||
LogValuesFunc: func(_ echo.Context, values middleware.RequestLoggerValues) error {
|
||||
path := values.RoutePath
|
||||
if path == "" {
|
||||
path = values.URIPath
|
||||
}
|
||||
log.Printf(
|
||||
"request_id=%s method=%s path=%s status=%d response_bytes=%d latency=%s",
|
||||
values.RequestID, values.Method, path, values.Status, values.ResponseSize, values.Latency,
|
||||
)
|
||||
return nil
|
||||
},
|
||||
}))
|
||||
e.Use(middleware.Recover())
|
||||
|
||||
e.GET("/health/live", h.liveness)
|
||||
e.GET("/health/ready", h.readiness)
|
||||
swaggerUI := echo.WrapHandler(v5emb.New(
|
||||
"MTUSI Messenger",
|
||||
"/swagger/openapi.json",
|
||||
"/swagger/",
|
||||
))
|
||||
e.GET("/swagger", h.swagger)
|
||||
e.GET("/swagger/", swaggerUI)
|
||||
e.GET("/swagger/openapi.json", h.swaggerSpec)
|
||||
e.GET("/swagger/*", swaggerUI)
|
||||
e.POST("/api/v1/users", h.createUser)
|
||||
|
||||
e.POST("/api/v1/auth/sessions", h.createSession)
|
||||
|
||||
api := e.Group("/api/v1", h.authenticate)
|
||||
api.GET("/users/me", h.currentUser)
|
||||
api.DELETE("/auth/sessions/current", h.deleteSession)
|
||||
api.POST("/chats", h.createChat)
|
||||
api.GET("/chats", h.listChats)
|
||||
api.GET("/chats/:chat_id", h.getChat)
|
||||
api.POST("/chats/:chat_id/messages", h.createMessage)
|
||||
api.GET("/chats/:chat_id/messages", h.listMessages)
|
||||
if h.attachments != nil {
|
||||
api.POST("/chats/:chat_id/attachments", h.uploadAttachment)
|
||||
api.GET("/attachments/:attachment_id", h.getAttachment)
|
||||
api.GET("/attachments/:attachment_id/content", h.attachmentContent)
|
||||
}
|
||||
|
||||
return e
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
package chat_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
chathandler "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository"
|
||||
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
|
||||
)
|
||||
|
||||
type testAPI struct {
|
||||
server *httptest.Server
|
||||
tokens sync.Map
|
||||
}
|
||||
|
||||
type userResponse struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
type chatResponse struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
type messageResponse struct {
|
||||
ID string `json:"id"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type messagePageResponse struct {
|
||||
Items []messageResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type errorResponse struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
func newTestAPI(t *testing.T) *testAPI {
|
||||
t.Helper()
|
||||
useCase := chatusecase.New(repository.NewMemory(), &testSessions{values: map[string]domain.Session{}}, time.Hour)
|
||||
server := httptest.NewServer(chathandler.NewChat(useCase, [32]byte{1}).Router())
|
||||
t.Cleanup(server.Close)
|
||||
return &testAPI{server: server}
|
||||
}
|
||||
|
||||
func (a *testAPI) request(t *testing.T, client *http.Client, method, path, actorID, body string, wantStatus int, target any) {
|
||||
t.Helper()
|
||||
request, err := http.NewRequest(method, a.server.URL+path, bytes.NewBufferString(body))
|
||||
if err != nil {
|
||||
t.Fatalf("create request: %v", err)
|
||||
}
|
||||
if body != "" {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
}
|
||||
if actorID != "" {
|
||||
token, _ := a.tokens.Load(actorID)
|
||||
request.Header.Set("Authorization", "Bearer "+token.(string))
|
||||
}
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("%s %s: %v", method, path, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
responseBody, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read response: %v", err)
|
||||
}
|
||||
if response.StatusCode != wantStatus {
|
||||
t.Fatalf("%s %s: status=%d, want=%d, body=%s", method, path, response.StatusCode, wantStatus, responseBody)
|
||||
}
|
||||
if response.Header.Get("X-Request-Id") == "" {
|
||||
t.Fatalf("%s %s: missing X-Request-Id", method, path)
|
||||
}
|
||||
if target != nil {
|
||||
if err := json.Unmarshal(responseBody, target); err != nil {
|
||||
t.Fatalf("decode response %q: %v", responseBody, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *testAPI) createUser(t *testing.T, username string) userResponse {
|
||||
t.Helper()
|
||||
var user userResponse
|
||||
a.request(t, http.DefaultClient, http.MethodPost, "/api/v1/users", "",
|
||||
fmt.Sprintf(`{"username":%q,"display_name":%q,"password":"test-password-12345"}`, username, username), http.StatusCreated, &user)
|
||||
req, err := http.NewRequest(http.MethodPost, a.server.URL+"/api/v1/auth/sessions", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":test-password-12345")))
|
||||
response, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
var login struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if response.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("login status: %d", response.StatusCode)
|
||||
}
|
||||
if err = json.NewDecoder(response.Body).Decode(&login); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a.tokens.Store(user.ID, login.Token)
|
||||
return user
|
||||
}
|
||||
|
||||
func (a *testAPI) requestError(t *testing.T, method, path, actorID, body string, wantStatus int, wantCode string) {
|
||||
t.Helper()
|
||||
var response errorResponse
|
||||
a.request(t, http.DefaultClient, method, path, actorID, body, wantStatus, &response)
|
||||
if response.Error.Code != wantCode {
|
||||
t.Fatalf("%s %s: error code=%q, want=%q", method, path, response.Error.Code, wantCode)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *testAPI) createChat(t *testing.T, ownerID string, memberIDs []string) chatResponse {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(map[string]any{"title": "test chat", "member_ids": memberIDs})
|
||||
if err != nil {
|
||||
t.Fatalf("encode chat: %v", err)
|
||||
}
|
||||
var chat chatResponse
|
||||
a.request(t, http.DefaultClient, http.MethodPost, "/api/v1/chats", ownerID, string(body), http.StatusCreated, &chat)
|
||||
return chat
|
||||
}
|
||||
|
||||
func (a *testAPI) createMessage(t *testing.T, client *http.Client, actorID, chatID, text string) messageResponse {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(map[string]string{"text": text})
|
||||
if err != nil {
|
||||
t.Fatalf("encode message: %v", err)
|
||||
}
|
||||
var message messageResponse
|
||||
a.request(t, client, http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actorID, string(body), http.StatusCreated, &message)
|
||||
return message
|
||||
}
|
||||
|
||||
func TestRejectsMalformedJSON(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.requestError(t, http.MethodPost, "/api/v1/users", "",
|
||||
`{"username":`, http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
|
||||
func TestHidesForeignChat(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
owner := api.createUser(t, "owner_user")
|
||||
outsider := api.createUser(t, "outsider_user")
|
||||
chat := api.createChat(t, owner.ID, []string{owner.ID})
|
||||
api.requestError(t, http.MethodGet, "/api/v1/chats/"+chat.ID, outsider.ID,
|
||||
"", http.StatusNotFound, "not_found")
|
||||
}
|
||||
|
||||
func TestRejectsEmptyMessage(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
user := api.createUser(t, "empty_message_user")
|
||||
chat := api.createChat(t, user.ID, []string{user.ID})
|
||||
api.requestError(t, http.MethodPost, "/api/v1/chats/"+chat.ID+"/messages", user.ID,
|
||||
`{"text":" "}`, http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
|
||||
func TestRejectsDuplicateUsername(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.createUser(t, "duplicate_user")
|
||||
api.requestError(t, http.MethodPost, "/api/v1/users", "",
|
||||
`{"username":"duplicate_user","display_name":"Duplicate","password":"test-password-12345"}`, http.StatusConflict, "conflict")
|
||||
}
|
||||
|
||||
func TestPaginatesMessagesAcrossMultiplePages(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
user := api.createUser(t, "pagination_user")
|
||||
chat := api.createChat(t, user.ID, []string{user.ID})
|
||||
for index := 0; index < 7; index++ {
|
||||
api.createMessage(t, http.DefaultClient, user.ID, chat.ID, fmt.Sprintf("message-%d", index))
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{})
|
||||
cursor := ""
|
||||
pageSizes := make([]int, 0, 4)
|
||||
for {
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages?limit=2"
|
||||
if cursor != "" {
|
||||
path += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
var page messagePageResponse
|
||||
api.request(t, http.DefaultClient, http.MethodGet, path, user.ID, "", http.StatusOK, &page)
|
||||
pageSizes = append(pageSizes, len(page.Items))
|
||||
for _, message := range page.Items {
|
||||
if _, duplicate := seen[message.ID]; duplicate {
|
||||
t.Fatalf("message %s appeared on multiple pages", message.ID)
|
||||
}
|
||||
seen[message.ID] = struct{}{}
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
if len(seen) != 7 {
|
||||
t.Fatalf("received %d unique messages, want 7", len(seen))
|
||||
}
|
||||
wantPageSizes := []int{2, 2, 2, 1}
|
||||
if fmt.Sprint(pageSizes) != fmt.Sprint(wantPageSizes) {
|
||||
t.Fatalf("page sizes=%v, want=%v", pageSizes, wantPageSizes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentMessagesAreUnique(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
|
||||
users := make([]userResponse, 10)
|
||||
memberIDs := make([]string, 10)
|
||||
for index := range users {
|
||||
users[index] = api.createUser(t, fmt.Sprintf("parallel_user_%02d", index))
|
||||
memberIDs[index] = users[index].ID
|
||||
}
|
||||
chat := api.createChat(t, users[0].ID, memberIDs)
|
||||
|
||||
start := make(chan struct{})
|
||||
errors := make(chan error, 10)
|
||||
var waitGroup sync.WaitGroup
|
||||
|
||||
for clientIndex := 0; clientIndex < 10; clientIndex++ {
|
||||
waitGroup.Add(1)
|
||||
go func(clientIndex int) {
|
||||
defer waitGroup.Done()
|
||||
client := &http.Client{Transport: &http.Transport{}, Timeout: 5 * time.Second}
|
||||
defer client.CloseIdleConnections()
|
||||
<-start
|
||||
for messageIndex := 0; messageIndex < 10; messageIndex++ {
|
||||
body, err := json.Marshal(map[string]string{
|
||||
"text": fmt.Sprintf("client-%02d-message-%02d", clientIndex, messageIndex),
|
||||
})
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
request, err := http.NewRequest(http.MethodPost,
|
||||
api.server.URL+"/api/v1/chats/"+chat.ID+"/messages", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
token, _ := api.tokens.Load(users[clientIndex].ID)
|
||||
request.Header.Set("Authorization", "Bearer "+token.(string))
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
_, readErr := io.Copy(io.Discard, response.Body)
|
||||
closeErr := response.Body.Close()
|
||||
if readErr != nil {
|
||||
errors <- readErr
|
||||
return
|
||||
}
|
||||
if closeErr != nil {
|
||||
errors <- closeErr
|
||||
return
|
||||
}
|
||||
if response.StatusCode != http.StatusCreated {
|
||||
errors <- fmt.Errorf("client %d message %d: status=%d", clientIndex, messageIndex, response.StatusCode)
|
||||
return
|
||||
}
|
||||
}
|
||||
}(clientIndex)
|
||||
}
|
||||
close(start)
|
||||
waitGroup.Wait()
|
||||
close(errors)
|
||||
for err := range errors {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
seenIDs := make(map[string]struct{}, 10*10)
|
||||
seenTexts := make(map[string]struct{}, 10*10)
|
||||
cursor := ""
|
||||
for {
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages?limit=17"
|
||||
if cursor != "" {
|
||||
path += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
var page messagePageResponse
|
||||
api.request(t, http.DefaultClient, http.MethodGet, path, users[0].ID, "", http.StatusOK, &page)
|
||||
for _, message := range page.Items {
|
||||
if _, duplicate := seenIDs[message.ID]; duplicate {
|
||||
t.Fatalf("duplicate message ID %s", message.ID)
|
||||
}
|
||||
if _, duplicate := seenTexts[message.Text]; duplicate {
|
||||
t.Fatalf("duplicate message text %q", message.Text)
|
||||
}
|
||||
seenIDs[message.ID] = struct{}{}
|
||||
seenTexts[message.Text] = struct{}{}
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
if len(seenIDs) != 10*10 || len(seenTexts) != 10*10 {
|
||||
t.Fatalf("received %d unique IDs and %d unique texts, want %d of each",
|
||||
len(seenIDs), len(seenTexts), 10*10)
|
||||
}
|
||||
}
|
||||
|
||||
// Session fake is only used by HTTP unit tests; the server always uses Redis.
|
||||
type testSessions struct {
|
||||
mu sync.Mutex
|
||||
values map[string]domain.Session
|
||||
}
|
||||
|
||||
func (s *testSessions) Ready(context.Context) error { return nil }
|
||||
func (s *testSessions) Put(_ context.Context, key string, value domain.Session) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.values[key] = value
|
||||
return nil
|
||||
}
|
||||
func (s *testSessions) Get(_ context.Context, key string) (domain.Session, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
value, ok := s.values[key]
|
||||
return value, ok, nil
|
||||
}
|
||||
func (s *testSessions) Delete(_ context.Context, key string) (bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
_, ok := s.values[key]
|
||||
delete(s.values, key)
|
||||
return ok, nil
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
)
|
||||
|
||||
func bearerToken(c echo.Context) string {
|
||||
parts := strings.Fields(c.Request().Header.Get("Authorization"))
|
||||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||||
return ""
|
||||
}
|
||||
return parts[1]
|
||||
}
|
||||
|
||||
func (h *Chat) createSession(c echo.Context) error {
|
||||
username, password, ok := c.Request().BasicAuth()
|
||||
if !ok {
|
||||
c.Response().Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
return h.writeError(c, http.StatusUnauthorized, "unauthorized", "Неверные учётные данные")
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(c.Request().Body, 1))
|
||||
if err != nil || len(body) != 0 {
|
||||
return h.invalid(c, "Тело запроса входа должно быть пустым")
|
||||
}
|
||||
login, err := h.useCase.CreateSession(c.Request().Context(), username, password)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, dto.CreateSessionResponse{
|
||||
Token: login.Token, TokenType: "Bearer", ExpiresAt: dto.Timestamp(login.ExpiresAt), User: createUserResponseFromDomain(login.User),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Chat) deleteSession(c echo.Context) error {
|
||||
if err := h.useCase.DeleteSession(c.Request().Context(), bearerToken(c)); err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
return c.NoContent(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/contracts"
|
||||
)
|
||||
|
||||
var swaggerOpenAPI = makeSwaggerOpenAPI()
|
||||
|
||||
func (h *Chat) swagger(c echo.Context) error {
|
||||
return c.Redirect(http.StatusTemporaryRedirect, "/swagger/")
|
||||
}
|
||||
|
||||
func (h *Chat) swaggerSpec(c echo.Context) error {
|
||||
return c.Blob(http.StatusOK, echo.MIMEApplicationJSON, swaggerOpenAPI)
|
||||
}
|
||||
|
||||
func makeSwaggerOpenAPI() []byte {
|
||||
var document map[string]any
|
||||
if err := json.Unmarshal(contracts.OpenAPI, &document); err != nil {
|
||||
panic("cannot decode embedded OpenAPI contract: " + err.Error())
|
||||
}
|
||||
// A relative URL keeps Swagger requests on the same scheme, host and port
|
||||
// as the UI. This also works behind a reverse proxy and on a custom PORT.
|
||||
document["servers"] = []map[string]string{{
|
||||
"url": "/",
|
||||
"description": "Текущий адрес Swagger UI",
|
||||
}}
|
||||
encoded, err := json.Marshal(document)
|
||||
if err != nil {
|
||||
panic("cannot encode Swagger OpenAPI contract: " + err.Error())
|
||||
}
|
||||
return encoded
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
// UseCase is the application boundary required by the HTTP handler.
|
||||
type UseCase interface {
|
||||
Ready(context.Context) error
|
||||
CreateSession(context.Context, string, string) (domain.Login, error)
|
||||
DeleteSession(context.Context, string) error
|
||||
Authenticate(ctx context.Context, token string) (domain.User, error)
|
||||
CreateUser(ctx context.Context, user domain.User, password string) (domain.User, error)
|
||||
CreateChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error)
|
||||
GetChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error)
|
||||
ListChats(ctx context.Context, callerID string, pagination domain.Pagination) (domain.ChatPage, error)
|
||||
CreateMessage(ctx context.Context, callerID string, message domain.Message) (domain.Message, error)
|
||||
ListMessages(ctx context.Context, callerID string, chat domain.Chat, pagination domain.Pagination) (domain.MessagePage, error)
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"mime"
|
||||
"os"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
const MaxBytes int64 = 10 * 1024 * 1024
|
||||
const MaxPixels int64 = 40_000_000
|
||||
|
||||
func appError(code domain.ErrorCode, message string) error {
|
||||
return domain.NewApplicationError(code, message)
|
||||
}
|
||||
func unavailable() error {
|
||||
return appError(domain.ErrorUnavailable, "Хранилище вложений недоступно")
|
||||
}
|
||||
func ValidateFilename(name string) error {
|
||||
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 255 {
|
||||
return appError(domain.ErrorInvalid, "Некорректный filename")
|
||||
}
|
||||
for _, r := range name {
|
||||
if r == '/' || r == '\\' || unicode.IsControl(r) {
|
||||
return appError(domain.ErrorInvalid, "Недопустимые символы filename")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Original struct {
|
||||
File *os.File
|
||||
Size int64
|
||||
SHA256, ContentType string
|
||||
Width, Height int
|
||||
}
|
||||
|
||||
func (o *Original) Close() { name := o.File.Name(); o.File.Close(); os.Remove(name) }
|
||||
|
||||
// Spool bounds compressed bytes on disk before any decode. DecodeConfig checks the
|
||||
// pixel budget before a full decode verifies CRCs/truncated scan data.
|
||||
func Spool(ctx context.Context, body io.Reader, declared string) (*Original, error) {
|
||||
media, _, err := mime.ParseMediaType(declared)
|
||||
if err != nil || (media != "image/png" && media != "image/jpeg") {
|
||||
return nil, appError("unsupported_media_type", "Допустимы PNG и JPEG")
|
||||
}
|
||||
f, err := os.CreateTemp("", "messenger-upload-*")
|
||||
if err != nil {
|
||||
return nil, unavailable()
|
||||
}
|
||||
o := &Original{File: f}
|
||||
good := false
|
||||
defer func() {
|
||||
if !good {
|
||||
o.Close()
|
||||
}
|
||||
}()
|
||||
hash := sha256.New()
|
||||
n, err := io.Copy(io.MultiWriter(f, hash), io.LimitReader(&contextReader{ctx: ctx, r: body}, MaxBytes+1))
|
||||
if n > MaxBytes {
|
||||
return nil, appError("payload_too_large", "Файл превышает 10 MiB")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, appError(domain.ErrorInvalid, "Загрузка прервана")
|
||||
}
|
||||
o.Size = n
|
||||
o.SHA256 = hex.EncodeToString(hash.Sum(nil))
|
||||
if _, err = f.Seek(0, 0); err != nil {
|
||||
return nil, unavailable()
|
||||
}
|
||||
cfg, format, err := image.DecodeConfig(f)
|
||||
if err != nil {
|
||||
return nil, appError("unsupported_media_type", "Повреждённое изображение")
|
||||
}
|
||||
actual := "image/" + format
|
||||
if actual != media {
|
||||
return nil, appError("unsupported_media_type", "MIME не соответствует содержимому")
|
||||
}
|
||||
if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width) > MaxPixels/int64(cfg.Height) {
|
||||
return nil, appError("payload_too_large", "Изображение превышает 40 миллионов пикселей")
|
||||
}
|
||||
if _, err = f.Seek(0, 0); err != nil {
|
||||
return nil, unavailable()
|
||||
}
|
||||
decoded, format, err := image.Decode(f)
|
||||
if err != nil || decoded == nil || "image/"+format != actual {
|
||||
return nil, appError("unsupported_media_type", "Повреждённое изображение")
|
||||
}
|
||||
if decoded.Bounds().Dx() != cfg.Width || decoded.Bounds().Dy() != cfg.Height {
|
||||
return nil, appError("unsupported_media_type", "Некорректные размеры изображения")
|
||||
}
|
||||
decoded = nil
|
||||
if _, err = f.Seek(0, 0); err != nil {
|
||||
return nil, unavailable()
|
||||
}
|
||||
o.ContentType = actual
|
||||
o.Width = cfg.Width
|
||||
o.Height = cfg.Height
|
||||
good = true
|
||||
return o, nil
|
||||
}
|
||||
|
||||
type contextReader struct {
|
||||
ctx context.Context
|
||||
r io.Reader
|
||||
}
|
||||
|
||||
func (r *contextReader) Read(p []byte) (int, error) {
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, err := r.r.Read(p)
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return n, err
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func pngFixture(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
m := image.NewRGBA(image.Rect(0, 0, 10, 8))
|
||||
m.Set(1, 1, color.RGBA{R: 255, A: 255})
|
||||
var b bytes.Buffer
|
||||
if err := png.Encode(&b, m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
func code(t *testing.T, err error, want domain.ErrorCode) {
|
||||
t.Helper()
|
||||
app, ok := domain.AsApplicationError(err)
|
||||
if !ok || app.Code != want {
|
||||
t.Fatalf("want %s, got %v", want, err)
|
||||
}
|
||||
}
|
||||
func TestSpoolOriginalAndFullValidation(t *testing.T) {
|
||||
original := pngFixture(t)
|
||||
good, err := Spool(context.Background(), bytes.NewReader(original), "image/png")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer good.Close()
|
||||
got, err := io.ReadAll(good.File)
|
||||
if err != nil || !bytes.Equal(got, original) {
|
||||
t.Fatal("original changed")
|
||||
}
|
||||
if good.Width != 10 || good.Height != 8 || good.Size != int64(len(original)) || len(good.SHA256) != 64 {
|
||||
t.Fatalf("wrong metadata %+v", good)
|
||||
}
|
||||
_, err = Spool(context.Background(), bytes.NewReader(original), "image/jpeg")
|
||||
code(t, err, "unsupported_media_type")
|
||||
_, err = Spool(context.Background(), bytes.NewReader(original[:len(original)-12]), "image/png")
|
||||
code(t, err, "unsupported_media_type")
|
||||
corrupted := bytes.Clone(original)
|
||||
corrupted[len(corrupted)-18] ^= 0x80
|
||||
_, err = Spool(context.Background(), bytes.NewReader(corrupted), "image/png")
|
||||
code(t, err, "unsupported_media_type")
|
||||
var jpegBytes bytes.Buffer
|
||||
if err = jpeg.Encode(&jpegBytes, image.NewRGBA(image.Rect(0, 0, 12, 9)), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
jpegOriginal, err := Spool(context.Background(), bytes.NewReader(jpegBytes.Bytes()), "image/jpeg")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
jpegOriginal.Close()
|
||||
_, err = Spool(context.Background(), bytes.NewReader(jpegBytes.Bytes()[:jpegBytes.Len()/2]), "image/jpeg")
|
||||
code(t, err, "unsupported_media_type")
|
||||
}
|
||||
func TestSpoolLimitsBeforeDecode(t *testing.T) {
|
||||
// Oversized compressed input is stopped after exactly MaxBytes+1 reads.
|
||||
source := &countingReader{remaining: MaxBytes + 100_000}
|
||||
_, err := Spool(context.Background(), source, "image/png")
|
||||
code(t, err, "payload_too_large")
|
||||
if source.read != MaxBytes+1 {
|
||||
t.Fatalf("read %d bytes", source.read)
|
||||
}
|
||||
bomb := bytes.Clone(pngFixture(t))
|
||||
binary.BigEndian.PutUint32(bomb[16:20], 40001)
|
||||
binary.BigEndian.PutUint32(bomb[20:24], 1000)
|
||||
binary.BigEndian.PutUint32(bomb[29:33], crc32.ChecksumIEEE(bomb[12:29]))
|
||||
_, err = Spool(context.Background(), bytes.NewReader(bomb), "image/png")
|
||||
code(t, err, "payload_too_large")
|
||||
}
|
||||
|
||||
type countingReader struct{ remaining, read int64 }
|
||||
|
||||
func (c *countingReader) Read(p []byte) (int, error) {
|
||||
if c.remaining == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := min(int64(len(p)), c.remaining)
|
||||
clear(p[:n])
|
||||
c.remaining -= n
|
||||
c.read += n
|
||||
return int(n), nil
|
||||
}
|
||||
func TestFilenameAndCancelledUpload(t *testing.T) {
|
||||
for _, name := range []string{"", "../x.png", "x\\photo.jpg", "a\x00b", "a\nb", "\t"} {
|
||||
code(t, ValidateFilename(name), domain.ErrorInvalid)
|
||||
}
|
||||
for _, name := range []string{"фото.png", "image.jpg", ".."} {
|
||||
if err := ValidateFilename(name); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err := Spool(ctx, bytes.NewReader(pngFixture(t)), "image/png")
|
||||
code(t, err, domain.ErrorInvalid)
|
||||
}
|
||||
func TestReconcileRejectsUnsafeGrace(t *testing.T) {
|
||||
s := &Service{}
|
||||
if _, err := s.Reconcile(context.Background(), true, 89*time.Second); err == nil {
|
||||
t.Fatal("unsafe grace accepted")
|
||||
}
|
||||
if MinimumGrace <= UploadTimeout {
|
||||
t.Fatal("grace does not cover in-flight PUT")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValid16BitWidePNG(t *testing.T) {
|
||||
// Exercise the same RGBA64 + scanline allocation path as an extreme-aspect
|
||||
// 40M image, at 1/1000 of that pixel count to keep the unit suite small.
|
||||
img := image.NewNRGBA64(image.Rect(0, 0, 40000, 1))
|
||||
img.SetNRGBA64(1, 0, color.NRGBA64{R: 65535, G: 12345, B: 4, A: 32000})
|
||||
var encoded bytes.Buffer
|
||||
if err := png.Encode(&encoded, img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original, err := Spool(context.Background(), bytes.NewReader(encoded.Bytes()), "image/png")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer original.Close()
|
||||
if original.Width != 40000 || original.Height != 1 {
|
||||
t.Fatal("wide PNG dimensions changed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
)
|
||||
|
||||
// MarshalJSON uses the API's fixed microsecond precision instead of time.Time's
|
||||
// variable fractional precision, which Python 3.9 clients cannot always parse.
|
||||
func (a Attachment) MarshalJSON() ([]byte, error) {
|
||||
type fields Attachment
|
||||
return json.Marshal(struct {
|
||||
fields
|
||||
CreatedAt dto.Timestamp `json:"created_at"`
|
||||
UpdatedAt dto.Timestamp `json:"updated_at"`
|
||||
}{fields: fields(a), CreatedAt: dto.Timestamp(a.CreatedAt), UpdatedAt: dto.Timestamp(a.UpdatedAt)})
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestAttachmentTimestampsUseFixedMicroseconds(t *testing.T) {
|
||||
value := Attachment{ID: "attachment-id", CreatedAt: time.Date(2026, 1, 2, 3, 4, 5, 123400000, time.UTC), UpdatedAt: time.Date(2026, 1, 2, 6, 4, 5, 0, time.FixedZone("MSK", 3*60*60)), Key: "original/private", Variants: []any{}}
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var fields map[string]any
|
||||
if err = json.Unmarshal(encoded, &fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fields["created_at"] != "2026-01-02T03:04:05.123400Z" {
|
||||
t.Fatalf("created_at=%v", fields["created_at"])
|
||||
}
|
||||
if fields["updated_at"] != "2026-01-02T03:04:05.000000Z" {
|
||||
t.Fatalf("updated_at=%v", fields["updated_at"])
|
||||
}
|
||||
if fields["id"] != value.ID {
|
||||
t.Fatal("serialization lost metadata")
|
||||
}
|
||||
if _, exposed := fields["Key"]; exposed {
|
||||
t.Fatal("serialization exposed private object key")
|
||||
}
|
||||
if _, exposed := fields["key"]; exposed {
|
||||
t.Fatal("serialization exposed private object key")
|
||||
}
|
||||
if fields["error_code"] != nil {
|
||||
t.Fatal("ready error_code must be null")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/minio/minio-go/v7"
|
||||
)
|
||||
|
||||
type Summary struct {
|
||||
Apply bool `json:"apply"`
|
||||
GraceSeconds float64 `json:"grace_seconds"`
|
||||
ObjectsScanned int `json:"objects_scanned"`
|
||||
MetadataScanned int `json:"metadata_scanned"`
|
||||
BytesScanned int64 `json:"bytes_scanned"`
|
||||
ListRequestsEstimate int `json:"list_requests_estimate"`
|
||||
StatRequests int `json:"stat_requests"`
|
||||
DBQueries int `json:"db_queries"`
|
||||
Orphans int `json:"orphans"`
|
||||
Missing int `json:"missing"`
|
||||
FreshSkipped int `json:"fresh_skipped"`
|
||||
LockedSkipped int `json:"locked_skipped"`
|
||||
ReferencedMissing int `json:"referenced_missing"`
|
||||
Deleted int `json:"deleted"`
|
||||
MarkedFailed int `json:"marked_failed"`
|
||||
DurationMS int64 `json:"duration_ms"`
|
||||
Actions []Action `json:"actions"`
|
||||
}
|
||||
type Action struct {
|
||||
Kind string `json:"kind"`
|
||||
Key string `json:"key"`
|
||||
Applied bool `json:"applied"`
|
||||
}
|
||||
|
||||
// Reconcile scans a fixed cutoff and rechecks each candidate while holding the
|
||||
// same transaction-scoped advisory lock as upload. Metadata, including message
|
||||
// references, is never deleted. Missing originals become failed tombstones.
|
||||
func (s *Service) Reconcile(ctx context.Context, apply bool, grace time.Duration) (result Summary, err error) {
|
||||
started := time.Now()
|
||||
result = Summary{Apply: apply, GraceSeconds: grace.Seconds(), Actions: []Action{}}
|
||||
defer func() { result.DurationMS = time.Since(started).Milliseconds() }()
|
||||
if grace < MinimumGrace {
|
||||
return result, fmt.Errorf("grace must be at least %s (upload timeout %s)", MinimumGrace, UploadTimeout)
|
||||
}
|
||||
cutoff := started.Add(-grace)
|
||||
for obj := range s.Store.Client.ListObjects(ctx, s.Store.Bucket, minio.ListObjectsOptions{Prefix: "original/", Recursive: true, MaxKeys: 1000}) {
|
||||
if obj.Err != nil {
|
||||
return result, fmt.Errorf("S3 listing failed")
|
||||
}
|
||||
result.ObjectsScanned++
|
||||
result.BytesScanned += obj.Size
|
||||
if result.ObjectsScanned%1000 == 1 {
|
||||
result.ListRequestsEstimate++
|
||||
}
|
||||
if !obj.LastModified.Before(cutoff) {
|
||||
result.FreshSkipped++
|
||||
continue
|
||||
}
|
||||
err = s.reconcileObject(ctx, obj.Key, cutoff, apply, &result)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
// Bounded keyset pages avoid retaining the entire bucket or a DB cursor while
|
||||
// making per-object transactions. A later run picks up concurrent new rows.
|
||||
last := "00000000-0000-0000-0000-000000000000"
|
||||
for {
|
||||
result.DBQueries++
|
||||
rows, e := s.Pool.Query(ctx, `SELECT id::text,object_key,created_at,status FROM attachments WHERE id>$1 ORDER BY id LIMIT 100`, last)
|
||||
if e != nil {
|
||||
return result, fmt.Errorf("metadata scan failed")
|
||||
}
|
||||
type metadata struct {
|
||||
id, key, status string
|
||||
created time.Time
|
||||
}
|
||||
page := []metadata{}
|
||||
for rows.Next() {
|
||||
var m metadata
|
||||
if e = rows.Scan(&m.id, &m.key, &m.created, &m.status); e != nil {
|
||||
rows.Close()
|
||||
return result, e
|
||||
}
|
||||
page = append(page, m)
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return result, e
|
||||
}
|
||||
if len(page) == 0 {
|
||||
break
|
||||
}
|
||||
for _, m := range page {
|
||||
last = m.id
|
||||
result.MetadataScanned++
|
||||
if m.status != "ready" {
|
||||
continue
|
||||
}
|
||||
if !m.created.Before(cutoff) {
|
||||
result.FreshSkipped++
|
||||
continue
|
||||
}
|
||||
if e = s.reconcileMetadata(ctx, m.id, m.key, cutoff, apply, &result); e != nil {
|
||||
return result, e
|
||||
}
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return result, ctx.Err()
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
func (s *Service) locked(ctx context.Context, key string, r *Summary) (pgx.Tx, bool, error) {
|
||||
tx, err := s.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("DB unavailable")
|
||||
}
|
||||
var locked bool
|
||||
r.DBQueries++
|
||||
if err = tx.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))`, key).Scan(&locked); err != nil {
|
||||
tx.Rollback(context.Background())
|
||||
return nil, false, fmt.Errorf("lock failed")
|
||||
}
|
||||
if !locked {
|
||||
r.LockedSkipped++
|
||||
tx.Rollback(context.Background())
|
||||
return nil, false, nil
|
||||
}
|
||||
return tx, true, nil
|
||||
}
|
||||
func (s *Service) reconcileObject(ctx context.Context, key string, cutoff time.Time, apply bool, r *Summary) error {
|
||||
tx, ok, err := s.locked(ctx, key, r)
|
||||
if err != nil || !ok {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var exists bool
|
||||
r.DBQueries++
|
||||
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1)`, key).Scan(&exists); err != nil {
|
||||
return fmt.Errorf("metadata recheck failed")
|
||||
}
|
||||
if exists {
|
||||
return nil
|
||||
}
|
||||
r.StatRequests++
|
||||
obj, err := s.Store.Client.StatObject(ctx, s.Store.Bucket, key, minio.StatObjectOptions{})
|
||||
if IsMissing(err) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("object recheck failed")
|
||||
}
|
||||
if !obj.LastModified.Before(cutoff) {
|
||||
r.FreshSkipped++
|
||||
return nil
|
||||
}
|
||||
r.Orphans++
|
||||
if apply {
|
||||
if err = s.Store.Client.RemoveObject(ctx, s.Store.Bucket, key, minio.RemoveObjectOptions{}); err != nil {
|
||||
return fmt.Errorf("orphan deletion failed")
|
||||
}
|
||||
r.Deleted++
|
||||
}
|
||||
if len(r.Actions) < 100 {
|
||||
r.Actions = append(r.Actions, Action{Kind: "orphan", Key: key, Applied: apply})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Service) reconcileMetadata(ctx context.Context, id, key string, cutoff time.Time, apply bool, r *Summary) error {
|
||||
tx, ok, err := s.locked(ctx, key, r)
|
||||
if err != nil || !ok {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var created time.Time
|
||||
var status string
|
||||
r.DBQueries++
|
||||
err = tx.QueryRow(ctx, `SELECT created_at,status FROM attachments WHERE id=$1 FOR UPDATE`, id).Scan(&created, &status)
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("metadata recheck failed")
|
||||
}
|
||||
if status != "ready" || !created.Before(cutoff) {
|
||||
return nil
|
||||
}
|
||||
r.StatRequests++
|
||||
_, err = s.Store.Client.StatObject(ctx, s.Store.Bucket, key, minio.StatObjectOptions{})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !IsMissing(err) {
|
||||
return fmt.Errorf("object stat failed (no mutation)")
|
||||
}
|
||||
var referenced bool
|
||||
r.DBQueries++
|
||||
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM messages WHERE $1::uuid=ANY(attachment_ids))`, id).Scan(&referenced); err != nil {
|
||||
return fmt.Errorf("reference check failed")
|
||||
}
|
||||
r.Missing++
|
||||
if referenced {
|
||||
r.ReferencedMissing++
|
||||
}
|
||||
if apply {
|
||||
r.DBQueries++
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='original_missing' WHERE id=$1 AND status='ready'`, id); err != nil {
|
||||
return fmt.Errorf("mark missing failed")
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit missing failed")
|
||||
}
|
||||
r.MarkedFailed++
|
||||
}
|
||||
if len(r.Actions) < 100 {
|
||||
r.Actions = append(r.Actions, Action{Kind: "missing", Key: key, Applied: apply})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
Client *minio.Client
|
||||
Bucket string
|
||||
}
|
||||
|
||||
func NewStore(endpoint, bucket, access, secret string, secure bool) (*Store, error) {
|
||||
transport := &http.Transport{Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{Timeout: 3 * time.Second, KeepAlive: 30 * time.Second}).DialContext, MaxIdleConns: 16, MaxIdleConnsPerHost: 8, IdleConnTimeout: 30 * time.Second, ResponseHeaderTimeout: 5 * time.Second, TLSHandshakeTimeout: 5 * time.Second, TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12}}
|
||||
c, err := minio.New(endpoint, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: secure, Region: "us-east-1", Transport: transport, MaxRetries: 1})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Store{Client: c, Bucket: bucket}, nil
|
||||
}
|
||||
func (s *Store) Ready(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
for item := range s.Client.ListObjects(ctx, s.Bucket, minio.ListObjectsOptions{Prefix: "original/", MaxKeys: 1, Recursive: true}) {
|
||||
if item.Err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return unavailable()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func IsMissing(err error) bool {
|
||||
code := minio.ToErrorResponse(err).Code
|
||||
return code == "NoSuchKey" || code == "NoSuchObject"
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/minio/minio-go/v7"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
const UploadTimeout = 45 * time.Second
|
||||
const MinimumGrace = 90 * time.Second
|
||||
|
||||
type Attachment struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
Size int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []any `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Key string `json:"-"`
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
Pool *pgxpool.Pool
|
||||
Store *Store
|
||||
slots chan struct{}
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, store *Store) *Service {
|
||||
return &Service{Pool: pool, Store: store, slots: make(chan struct{}, 1)}
|
||||
}
|
||||
func (s *Service) Ready(ctx context.Context) error { return s.Store.Ready(ctx) }
|
||||
func (s *Service) Upload(ctx context.Context, chatID, userID, name, contentType string, body io.Reader) (Attachment, error) {
|
||||
if err := ValidateFilename(name); err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, UploadTimeout)
|
||||
defer cancel()
|
||||
select {
|
||||
case s.slots <- struct{}{}:
|
||||
defer func() { <-s.slots }()
|
||||
case <-ctx.Done():
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
original, err := Spool(ctx, body, contentType)
|
||||
if err != nil {
|
||||
return Attachment{}, err
|
||||
}
|
||||
defer original.Close()
|
||||
a := Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: name, ContentType: original.ContentType, Size: original.Size, SHA256: original.SHA256, Status: "ready", Variants: []any{}}
|
||||
a.Key = "original/" + a.ID
|
||||
tx, err := s.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
// Keep the object lock through PUT, metadata insert and COMMIT. A crash releases
|
||||
// the lock; the grace protects a still-running client PUT at the S3 server.
|
||||
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, a.Key); err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
_, err = s.Store.Client.PutObject(ctx, s.Store.Bucket, a.Key, original.File, a.Size, minio.PutObjectOptions{ContentType: a.ContentType, DisableMultipart: true, UserMetadata: map[string]string{"sha256": a.SHA256}})
|
||||
if err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
err = tx.QueryRow(ctx, `INSERT INTO attachments(id,chat_id,uploader_id,filename,object_key,content_type,size_bytes,sha256,width,height) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING created_at`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.Key, a.ContentType, a.Size, a.SHA256, original.Width, original.Height).Scan(&a.CreatedAt)
|
||||
if err != nil {
|
||||
log.Print("attachment metadata failed; orphan retained for grace-period reconciliation")
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
// Never DELETE on an ambiguous COMMIT failure: the DB may have committed. A
|
||||
// later reconciler checks both stores under the same lock before any cleanup.
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
a.UpdatedAt = a.CreatedAt
|
||||
return a, nil
|
||||
}
|
||||
func (s *Service) Get(ctx context.Context, id, userID string) (Attachment, error) {
|
||||
parsed, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
return Attachment{}, appError(domain.ErrorInvalid, "Некорректный attachment_id")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
a := Attachment{Variants: []any{}}
|
||||
err = s.Pool.QueryRow(ctx, `SELECT a.id::text,a.chat_id::text,a.uploader_id::text,a.filename,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status,a.error_code,a.created_at FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id WHERE a.id=$1 AND m.user_id=$2`, parsed.String(), userID).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.Key, &a.ContentType, &a.Size, &a.SHA256, &a.Status, &a.ErrorCode, &a.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return Attachment{}, appError(domain.ErrorNotFound, "Объект не найден")
|
||||
}
|
||||
if err != nil {
|
||||
return Attachment{}, unavailable()
|
||||
}
|
||||
a.UpdatedAt = a.CreatedAt
|
||||
// Keep the mandatory lab4 ready-only metadata schema. Failed originals are
|
||||
// represented by 409; internal status remains inspectable in reconciliation.
|
||||
if a.Status != "ready" {
|
||||
return Attachment{}, appError(domain.ErrorConflict, "Оригинал вложения недоступен")
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
func (s *Service) Content(ctx context.Context, a Attachment) (*minio.Object, error) {
|
||||
if a.Status != "ready" {
|
||||
return nil, appError(domain.ErrorConflict, "Вложение не готово")
|
||||
}
|
||||
obj, err := s.Store.Client.GetObject(ctx, s.Store.Bucket, a.Key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, unavailable()
|
||||
}
|
||||
if _, err = obj.Stat(); err != nil {
|
||||
obj.Close()
|
||||
if IsMissing(err) {
|
||||
return nil, appError(domain.ErrorConflict, "Оригинал вложения недоступен")
|
||||
}
|
||||
return nil, unavailable()
|
||||
}
|
||||
return obj, nil
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
S3Endpoint string
|
||||
S3Bucket string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
S3UseSSL bool
|
||||
Port string
|
||||
PostgresHost string
|
||||
PostgresPort uint16
|
||||
PostgresUser string
|
||||
PostgresDatabase string
|
||||
PostgresPassword string
|
||||
PostgresMaxConns int32
|
||||
RedisAddr string
|
||||
SessionTTL time.Duration
|
||||
QueryTimeout time.Duration
|
||||
CursorKey [32]byte
|
||||
}
|
||||
|
||||
func value(name, fallback string) string {
|
||||
if v := os.Getenv(name); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
func positive(name string, fallback, max int) (int, error) {
|
||||
n, err := strconv.Atoi(value(name, strconv.Itoa(fallback)))
|
||||
if err != nil || n < 1 || n > max {
|
||||
return 0, fmt.Errorf("invalid %s", name)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
func secret(name string) (string, error) {
|
||||
if file := os.Getenv(name + "_FILE"); file != "" {
|
||||
data, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot read %s_FILE", name)
|
||||
}
|
||||
if s := strings.TrimSpace(string(data)); s != "" {
|
||||
return s, nil
|
||||
}
|
||||
}
|
||||
if s := os.Getenv(name); s != "" {
|
||||
return s, nil
|
||||
}
|
||||
return "", fmt.Errorf("%s or %s_FILE is required", name, name)
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
var c Config
|
||||
port, err := positive("PORT", 8080, 65535)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.Port = strconv.Itoa(port)
|
||||
pgPort, err := positive("POSTGRES_PORT", 5432, 65535)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.PostgresPort = uint16(pgPort)
|
||||
max, err := positive("POSTGRES_MAX_CONNS", 10, 100)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.PostgresMaxConns = int32(max)
|
||||
ttl, err := positive("SESSION_TTL_SECONDS", 3600, 86400*30)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.SessionTTL = time.Duration(ttl) * time.Second
|
||||
timeout, err := positive("QUERY_TIMEOUT_MS", 2000, 10000)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.QueryTimeout = time.Duration(timeout) * time.Millisecond
|
||||
c.PostgresHost = value("POSTGRES_HOST", "localhost")
|
||||
c.PostgresUser = value("POSTGRES_USER", "messenger")
|
||||
c.PostgresDatabase = value("POSTGRES_DB", "messenger")
|
||||
c.RedisAddr = value("REDIS_ADDR", "localhost:6379")
|
||||
c.PostgresPassword, err = secret("POSTGRES_PASSWORD")
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
key, err := secret("CURSOR_KEY")
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
decoded, err := hex.DecodeString(key)
|
||||
if err != nil || len(decoded) != 32 {
|
||||
return c, fmt.Errorf("CURSOR_KEY must be 32 random bytes encoded as hex")
|
||||
}
|
||||
copy(c.CursorKey[:], decoded)
|
||||
c.S3Endpoint = value("S3_ENDPOINT", "minio:9000")
|
||||
c.S3Bucket = value("S3_BUCKET", "attachments")
|
||||
c.S3UseSSL, err = strconv.ParseBool(value("S3_USE_SSL", "false"))
|
||||
if err != nil {
|
||||
return c, fmt.Errorf("invalid S3_USE_SSL")
|
||||
}
|
||||
c.S3AccessKey, err = secret("S3_ACCESS_KEY")
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.S3SecretKey, err = secret("S3_SECRET_KEY")
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Chat struct {
|
||||
ID string
|
||||
Title string
|
||||
MemberIDs []string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package domain
|
||||
|
||||
import "errors"
|
||||
|
||||
type ErrorCode string
|
||||
|
||||
const (
|
||||
ErrorUnavailable ErrorCode = "unavailable"
|
||||
ErrorInvalid ErrorCode = "invalid_request"
|
||||
ErrorUnauthorized ErrorCode = "unauthorized"
|
||||
ErrorNotFound ErrorCode = "not_found"
|
||||
ErrorConflict ErrorCode = "conflict"
|
||||
)
|
||||
|
||||
type ApplicationError struct {
|
||||
Code ErrorCode
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *ApplicationError) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
func NewApplicationError(code ErrorCode, message string) error {
|
||||
return &ApplicationError{Code: code, Message: message}
|
||||
}
|
||||
|
||||
func AsApplicationError(err error) (*ApplicationError, bool) {
|
||||
var applicationError *ApplicationError
|
||||
ok := errors.As(err, &applicationError)
|
||||
return applicationError, ok
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Message struct {
|
||||
IdempotencyKey string
|
||||
ID string
|
||||
ChatID string
|
||||
SenderID string
|
||||
AttachmentIDs []string
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Position struct {
|
||||
CreatedAt time.Time
|
||||
ID string
|
||||
}
|
||||
|
||||
type Pagination struct {
|
||||
After *Position
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ChatPage struct {
|
||||
Items []Chat
|
||||
HasMore bool
|
||||
}
|
||||
|
||||
type MessagePage struct {
|
||||
Items []Message
|
||||
HasMore bool
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Session struct {
|
||||
UserID string `json:"user_id"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
type Login struct {
|
||||
Token string
|
||||
ExpiresAt time.Time
|
||||
User User
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
ID string
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
// Bound simultaneous KDF work to 4 * 19 MiB, including concurrent registrations.
|
||||
var slots = make(chan struct{}, 4)
|
||||
|
||||
const prefix = "$argon2id$v=19$m=19456,t=2,p=1$"
|
||||
|
||||
func derive(ctx context.Context, password string, salt []byte) ([]byte, error) {
|
||||
select {
|
||||
case slots <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
defer func() { <-slots }()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return argon2.IDKey([]byte(password), salt, 2, 19456, 1, 32), nil
|
||||
}
|
||||
|
||||
func Hash(ctx context.Context, password string) (string, error) {
|
||||
salt := make([]byte, 16)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
key, err := derive(ctx, password, salt)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return prefix + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(key), nil
|
||||
}
|
||||
|
||||
func Verify(ctx context.Context, password, encoded string) (bool, error) {
|
||||
if !strings.HasPrefix(encoded, prefix) {
|
||||
return false, errors.New("unsupported password hash")
|
||||
}
|
||||
parts := strings.Split(strings.TrimPrefix(encoded, prefix), "$")
|
||||
if len(parts) != 2 {
|
||||
return false, errors.New("invalid password hash")
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[0])
|
||||
if err != nil || len(salt) != 16 {
|
||||
return false, errors.New("invalid salt")
|
||||
}
|
||||
expected, err := base64.RawStdEncoding.DecodeString(parts[1])
|
||||
if err != nil || len(expected) != 32 {
|
||||
return false, errors.New("invalid hash")
|
||||
}
|
||||
actual, err := derive(ctx, password, salt)
|
||||
return subtle.ConstantTimeCompare(actual, expected) == 1, err
|
||||
}
|
||||
|
||||
// A valid fixed encoding for equal-cost verification when username does not exist.
|
||||
const DummyHash = prefix + "AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||
@@ -0,0 +1,35 @@
|
||||
package password_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
|
||||
)
|
||||
|
||||
func TestUnicodeAndSalt(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
secret := strings.Repeat("🔑", 128)
|
||||
first, err := password.Hash(ctx, secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := password.Hash(ctx, secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first == second {
|
||||
t.Fatal("password hashes reused salt")
|
||||
}
|
||||
for _, hash := range []string{first, second} {
|
||||
ok, err := password.Verify(ctx, secret, hash)
|
||||
if err != nil || !ok {
|
||||
t.Fatal("128-code-point UTF-8 password rejected")
|
||||
}
|
||||
ok, err = password.Verify(ctx, strings.Repeat("🔑", 127)+"x", hash)
|
||||
if err != nil || ok {
|
||||
t.Fatal("password suffix was ignored")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
|
||||
)
|
||||
|
||||
// Memory is the lab1 in-memory Repository implementation.
|
||||
type Memory struct {
|
||||
mu sync.RWMutex
|
||||
users map[string]domain.User
|
||||
hashes map[string]string
|
||||
userByUsername map[string]string
|
||||
chats map[string]domain.Chat
|
||||
messages map[string][]domain.Message
|
||||
}
|
||||
|
||||
var _ chatusecase.Repository = (*Memory)(nil)
|
||||
|
||||
func NewMemory() *Memory {
|
||||
return &Memory{
|
||||
users: make(map[string]domain.User),
|
||||
hashes: make(map[string]string),
|
||||
userByUsername: make(map[string]string),
|
||||
chats: make(map[string]domain.Chat),
|
||||
messages: make(map[string][]domain.Message),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Memory) CreateUser(_ context.Context, username, displayName, hash string) (domain.User, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if _, exists := m.userByUsername[username]; exists {
|
||||
return domain.User{}, chatusecase.ErrUsernameTaken
|
||||
}
|
||||
user := domain.User{
|
||||
ID: uuid.NewString(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: now(),
|
||||
}
|
||||
m.users[user.ID] = user
|
||||
m.hashes[user.ID] = hash
|
||||
m.userByUsername[user.Username] = user.ID
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (m *Memory) User(_ context.Context, id string) (domain.User, bool, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
user, ok := m.users[id]
|
||||
return user, ok, nil
|
||||
}
|
||||
|
||||
func (m *Memory) CreateChat(_ context.Context, title string, memberIDs []string) (domain.Chat, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
for _, memberID := range memberIDs {
|
||||
if _, exists := m.users[memberID]; !exists {
|
||||
return domain.Chat{}, chatusecase.ErrUserNotFound
|
||||
}
|
||||
}
|
||||
chat := domain.Chat{
|
||||
ID: uuid.NewString(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
CreatedAt: now(),
|
||||
}
|
||||
m.chats[chat.ID] = chat
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (m *Memory) ChatForUser(_ context.Context, chatID, userID string) (domain.Chat, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
chat, exists := m.chats[chatID]
|
||||
if !exists {
|
||||
return domain.Chat{}, chatusecase.ErrChatNotFound
|
||||
}
|
||||
if !contains(chat.MemberIDs, userID) {
|
||||
return domain.Chat{}, chatusecase.ErrNotMember
|
||||
}
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (m *Memory) ListChats(_ context.Context, userID string, after *domain.Position, limit int) ([]domain.Chat, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
result := make([]domain.Chat, 0)
|
||||
for _, chat := range m.chats {
|
||||
if contains(chat.MemberIDs, userID) && isAfter(chat.CreatedAt, chat.ID, after) {
|
||||
result = append(result, cloneChat(chat))
|
||||
}
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
return less(result[i].CreatedAt, result[i].ID, result[j].CreatedAt, result[j].ID)
|
||||
})
|
||||
if len(result) > limit {
|
||||
result = result[:limit]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (m *Memory) CreateMessage(_ context.Context, chatID, senderID, text, key string) (domain.Message, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
chat, exists := m.chats[chatID]
|
||||
if !exists {
|
||||
return domain.Message{}, chatusecase.ErrChatNotFound
|
||||
}
|
||||
if !contains(chat.MemberIDs, senderID) {
|
||||
return domain.Message{}, chatusecase.ErrNotMember
|
||||
}
|
||||
if key != "" {
|
||||
for _, previous := range m.messages[chatID] {
|
||||
if previous.SenderID == senderID && previous.IdempotencyKey == key {
|
||||
if previous.Text != text {
|
||||
return domain.Message{}, domain.NewApplicationError(domain.ErrorConflict, "Idempotency-Key уже использован с другим телом")
|
||||
}
|
||||
return previous, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
message := domain.Message{
|
||||
IdempotencyKey: key,
|
||||
ID: uuid.NewString(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: now(),
|
||||
}
|
||||
m.messages[chatID] = append(m.messages[chatID], message)
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (m *Memory) ListMessages(_ context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
values := m.messages[chatID]
|
||||
result := make([]domain.Message, 0, min(len(values), limit))
|
||||
for _, message := range values {
|
||||
if isAfter(message.CreatedAt, message.ID, after) {
|
||||
result = append(result, message)
|
||||
}
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
return less(result[i].CreatedAt, result[i].ID, result[j].CreatedAt, result[j].ID)
|
||||
})
|
||||
if len(result) > limit {
|
||||
result = result[:limit]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func cloneChat(chat domain.Chat) domain.Chat {
|
||||
chat.MemberIDs = append([]string(nil), chat.MemberIDs...)
|
||||
return chat
|
||||
}
|
||||
|
||||
func now() time.Time {
|
||||
return time.Now().UTC().Truncate(time.Second)
|
||||
}
|
||||
|
||||
func contains(values []string, target string) bool {
|
||||
for _, value := range values {
|
||||
if value == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isAfter(createdAt time.Time, id string, after *domain.Position) bool {
|
||||
return after == nil || createdAt.After(after.CreatedAt) || createdAt.Equal(after.CreatedAt) && id > after.ID
|
||||
}
|
||||
|
||||
func less(leftTime time.Time, leftID string, rightTime time.Time, rightID string) bool {
|
||||
if leftTime.Equal(rightTime) {
|
||||
return leftID < rightID
|
||||
}
|
||||
return leftTime.Before(rightTime)
|
||||
}
|
||||
|
||||
func (m *Memory) Ready(context.Context) error { return nil }
|
||||
func (m *Memory) UserByUsername(_ context.Context, username string) (domain.User, string, bool, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
id, ok := m.userByUsername[username]
|
||||
return m.users[id], m.hashes[id], ok, nil
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
|
||||
)
|
||||
|
||||
func (s *Storage) CreateChat(ctx context.Context, title string, members []string) (domain.Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return domain.Chat{}, dbError(err)
|
||||
}
|
||||
defer tx.Rollback(context.WithoutCancel(ctx))
|
||||
chat := domain.Chat{ID: uuid.NewString(), Title: title, MemberIDs: append([]string(nil), members...)}
|
||||
err = tx.QueryRow(ctx, `INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at`, chat.ID, title).Scan(&chat.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Chat{}, dbError(err)
|
||||
}
|
||||
for i, member := range members {
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id,ordinal) VALUES($1,$2,$3)`, chat.ID, member, i); err != nil {
|
||||
return domain.Chat{}, dbError(err)
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return domain.Chat{}, dbError(err)
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
const chatColumns = `c.id::text,c.title,c.created_at,ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.ordinal)`
|
||||
|
||||
func (s *Storage) ChatForUser(ctx context.Context, chatID, userID string) (domain.Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var chat domain.Chat
|
||||
err := s.pool.QueryRow(ctx, `SELECT `+chatColumns+` FROM chats c
|
||||
WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members m WHERE m.chat_id=c.id AND m.user_id=$2)`, chatID, userID).
|
||||
Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return chat, chatusecase.ErrChatNotFound
|
||||
}
|
||||
return chat, dbError(err)
|
||||
}
|
||||
|
||||
func (s *Storage) ListChats(ctx context.Context, userID string, after *domain.Position, limit int) ([]domain.Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
query := `SELECT ` + chatColumns + ` FROM chats c JOIN chat_members member ON member.chat_id=c.id
|
||||
WHERE member.user_id=$1`
|
||||
args := []any{userID, limit}
|
||||
if after != nil {
|
||||
query += ` AND (c.created_at,c.id)>($3,$4)`
|
||||
args = append(args, after.CreatedAt, after.ID)
|
||||
}
|
||||
query += ` ORDER BY c.created_at,c.id LIMIT $2`
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
chats := make([]domain.Chat, 0)
|
||||
for rows.Next() {
|
||||
var chat domain.Chat
|
||||
if err = rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
chats = append(chats, chat)
|
||||
}
|
||||
return chats, dbError(rows.Err())
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
type fakeObject struct {
|
||||
data []byte
|
||||
modified time.Time
|
||||
}
|
||||
type fakeS3 struct {
|
||||
mu sync.Mutex
|
||||
objects map[string]fakeObject
|
||||
failPUT bool
|
||||
}
|
||||
|
||||
func (f *fakeS3) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
key := strings.TrimPrefix(r.URL.Path, "/attachments/")
|
||||
if r.Method == "GET" && r.URL.Path == "/attachments/" || r.Method == "GET" && r.URL.Path == "/attachments" {
|
||||
type item struct {
|
||||
Key string
|
||||
LastModified string
|
||||
ETag string
|
||||
Size int
|
||||
}
|
||||
type listing struct {
|
||||
XMLName xml.Name `xml:"ListBucketResult"`
|
||||
Xmlns string `xml:"xmlns,attr"`
|
||||
Name string
|
||||
Prefix string
|
||||
MaxKeys int
|
||||
IsTruncated bool
|
||||
Contents []item
|
||||
}
|
||||
l := listing{Xmlns: "http://s3.amazonaws.com/doc/2006-03-01/", Name: "attachments", Prefix: r.URL.Query().Get("prefix"), MaxKeys: 1000}
|
||||
for k, v := range f.objects {
|
||||
if strings.HasPrefix(k, l.Prefix) {
|
||||
l.Contents = append(l.Contents, item{Key: k, LastModified: v.modified.UTC().Format("2006-01-02T15:04:05.000Z"), ETag: `"abc"`, Size: len(v.data)})
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
xml.NewEncoder(w).Encode(l)
|
||||
return
|
||||
}
|
||||
if r.Method == "PUT" {
|
||||
if f.failPUT {
|
||||
w.WriteHeader(503)
|
||||
fmt.Fprint(w, `<Error><Code>ServiceUnavailable</Code></Error>`)
|
||||
return
|
||||
}
|
||||
var data []byte
|
||||
var err error
|
||||
if strings.Contains(r.Header.Get("Content-Encoding"), "aws-chunked") || strings.HasPrefix(r.Header.Get("X-Amz-Content-Sha256"), "STREAMING-") {
|
||||
reader := bufio.NewReader(r.Body)
|
||||
for {
|
||||
line, e := reader.ReadString('\n')
|
||||
if e != nil {
|
||||
err = e
|
||||
break
|
||||
}
|
||||
size, e := strconv.ParseInt(strings.Split(strings.TrimSpace(line), ";")[0], 16, 64)
|
||||
if e != nil {
|
||||
err = e
|
||||
break
|
||||
}
|
||||
if size == 0 {
|
||||
break
|
||||
}
|
||||
chunk := make([]byte, size)
|
||||
if _, e = io.ReadFull(reader, chunk); e != nil {
|
||||
err = e
|
||||
break
|
||||
}
|
||||
data = append(data, chunk...)
|
||||
if _, e = reader.Discard(2); e != nil {
|
||||
err = e
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
data, err = io.ReadAll(r.Body)
|
||||
}
|
||||
if err != nil {
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
f.objects[key] = fakeObject{data: data, modified: time.Now().UTC()}
|
||||
w.Header().Set("ETag", `"900150983cd24fb0d6963f7d28e17f72"`)
|
||||
w.WriteHeader(200)
|
||||
return
|
||||
}
|
||||
obj, ok := f.objects[key]
|
||||
if !ok {
|
||||
w.WriteHeader(404)
|
||||
if r.Method != "HEAD" {
|
||||
fmt.Fprint(w, `<Error><Code>NoSuchKey</Code></Error>`)
|
||||
}
|
||||
return
|
||||
}
|
||||
if r.Method == "DELETE" {
|
||||
delete(f.objects, key)
|
||||
w.WriteHeader(204)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Last-Modified", obj.modified.UTC().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", `"abc"`)
|
||||
w.Header().Set("Content-Length", fmt.Sprint(len(obj.data)))
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
if r.Method == "GET" {
|
||||
w.Write(obj.data)
|
||||
}
|
||||
}
|
||||
func lab4Backend(t *testing.T, pool *pgxpool.Pool, repo *postgres.Storage, user domain.User, chat domain.Chat) {
|
||||
ctx := context.Background()
|
||||
fake := &fakeS3{objects: map[string]fakeObject{}}
|
||||
server := httptest.NewServer(fake)
|
||||
defer server.Close()
|
||||
client, err := minio.New(strings.TrimPrefix(server.URL, "http://"), &minio.Options{Creds: credentials.NewStaticV4("test-key", "test-secret", ""), Region: "us-east-1", MaxRetries: 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := attachment.New(pool, &attachment.Store{Client: client, Bucket: "attachments"})
|
||||
var imageBytes bytes.Buffer
|
||||
if err = png.Encode(&imageBytes, image.NewRGBA(image.Rect(0, 0, 10, 8))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
upload := func(name string) attachment.Attachment {
|
||||
t.Helper()
|
||||
a, e := service.Upload(ctx, chat.ID, user.ID, name, "image/png", bytes.NewReader(imageBytes.Bytes()))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return a
|
||||
}
|
||||
first := upload("first.png")
|
||||
second := upload("second.png")
|
||||
requireCode := func(err error, want domain.ErrorCode) {
|
||||
t.Helper()
|
||||
e, ok := domain.AsApplicationError(err)
|
||||
if !ok || e.Code != want {
|
||||
t.Fatalf("expected %s, got %v", want, err)
|
||||
}
|
||||
}
|
||||
outside, err := repo.CreateUser(ctx, "attachment_outsider", "Outside", "hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = service.Get(ctx, first.ID, outside.ID)
|
||||
requireCode(err, domain.ErrorNotFound)
|
||||
obj, err := service.Content(ctx, first)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := io.ReadAll(obj)
|
||||
obj.Close()
|
||||
if err != nil || !bytes.Equal(data, imageBytes.Bytes()) {
|
||||
t.Fatalf("original mismatch: %v", err)
|
||||
}
|
||||
otherChat, err := repo.CreateChat(ctx, "Other", []string{user.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = repo.CreateMessageWithAttachments(ctx, otherChat.ID, user.ID, "", "cross-chat", []string{first.ID})
|
||||
requireCode(err, domain.ErrorNotFound)
|
||||
_, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "unknown", []string{uuid.NewString()})
|
||||
requireCode(err, domain.ErrorNotFound)
|
||||
sent, err := repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "ordered", []string{first.ID, second.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replay, err := repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "ordered", []string{first.ID, second.ID})
|
||||
if err != nil || sent.ID != replay.ID {
|
||||
t.Fatalf("replay failed: %v", err)
|
||||
}
|
||||
_, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "ordered", []string{second.ID, first.ID})
|
||||
requireCode(err, domain.ErrorConflict)
|
||||
textOnly, err := repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "text", "empty-equivalent", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replay, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "text", "empty-equivalent", []string{})
|
||||
if err != nil || textOnly.ID != replay.ID {
|
||||
t.Fatalf("absent/empty differs: %v", err)
|
||||
}
|
||||
|
||||
const callers = 12
|
||||
outcomes := make(chan domain.Message, callers)
|
||||
failures := make(chan error, callers)
|
||||
var concurrent sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for i := 0; i < callers; i++ {
|
||||
concurrent.Add(1)
|
||||
go func() {
|
||||
defer concurrent.Done()
|
||||
<-start
|
||||
m, e := repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "concurrent-attachments", []string{first.ID, second.ID})
|
||||
if e != nil {
|
||||
failures <- e
|
||||
} else {
|
||||
outcomes <- m
|
||||
}
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
concurrent.Wait()
|
||||
close(outcomes)
|
||||
close(failures)
|
||||
for e := range failures {
|
||||
t.Fatal(e)
|
||||
}
|
||||
identity := ""
|
||||
for m := range outcomes {
|
||||
if identity == "" {
|
||||
identity = m.ID
|
||||
}
|
||||
if m.ID != identity {
|
||||
t.Fatal("duplicate concurrent attachment message")
|
||||
}
|
||||
}
|
||||
var effects int
|
||||
if err = pool.QueryRow(ctx, `SELECT count(*) FROM messages WHERE chat_id=$1 AND idempotency_key='concurrent-attachments'`, chat.ID).Scan(&effects); err != nil || effects != 1 {
|
||||
t.Fatalf("concurrent effects=%d %v", effects, err)
|
||||
}
|
||||
t.Log("ACL, original bytes, cross-chat attachment rejection, ordered/concurrent idempotency and absent=[] passed")
|
||||
|
||||
old := time.Now().Add(-3 * time.Minute)
|
||||
orphan := "original/" + uuid.NewString()
|
||||
fresh := "original/" + uuid.NewString()
|
||||
locked := "original/" + uuid.NewString()
|
||||
fake.mu.Lock()
|
||||
delete(fake.objects, first.Key)
|
||||
v := fake.objects[second.Key]
|
||||
v.modified = old
|
||||
fake.objects[second.Key] = v
|
||||
fake.objects[orphan] = fakeObject{data: []byte("orphan"), modified: old}
|
||||
fake.objects[fresh] = fakeObject{data: []byte("fresh"), modified: time.Now()}
|
||||
fake.objects[locked] = fakeObject{data: []byte("locked"), modified: old}
|
||||
fake.mu.Unlock()
|
||||
if _, err = pool.Exec(ctx, `UPDATE attachments SET created_at=$1 WHERE id=ANY($2::uuid[])`, old, []string{first.ID, second.ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hold, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer hold.Rollback(ctx)
|
||||
if _, err = hold.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, locked); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dry, err := service.Reconcile(ctx, false, 90*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dry.Orphans != 1 || dry.Missing != 1 || dry.ReferencedMissing != 1 || dry.LockedSkipped != 1 || dry.FreshSkipped < 1 || dry.Deleted != 0 || dry.MarkedFailed != 0 {
|
||||
t.Fatalf("bad dry-run %+v", dry)
|
||||
}
|
||||
var status string
|
||||
if err = pool.QueryRow(ctx, `SELECT status FROM attachments WHERE id=$1`, first.ID).Scan(&status); err != nil || status != "ready" {
|
||||
t.Fatalf("dry-run mutated metadata %s %v", status, err)
|
||||
}
|
||||
applied, err := service.Reconcile(ctx, true, 90*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if applied.Deleted != 1 || applied.MarkedFailed != 1 {
|
||||
t.Fatalf("bad apply %+v", applied)
|
||||
}
|
||||
fake.mu.Lock()
|
||||
_, hasOrphan := fake.objects[orphan]
|
||||
_, hasFresh := fake.objects[fresh]
|
||||
_, hasLinked := fake.objects[second.Key]
|
||||
_, hasLocked := fake.objects[locked]
|
||||
fake.mu.Unlock()
|
||||
if hasOrphan || !hasFresh || !hasLinked || !hasLocked {
|
||||
t.Fatal("unsafe object cleanup")
|
||||
}
|
||||
_, err = service.Get(ctx, first.ID, user.ID)
|
||||
requireCode(err, domain.ErrorConflict)
|
||||
_, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "failed-attachment", []string{first.ID})
|
||||
requireCode(err, domain.ErrorConflict)
|
||||
replay, err = repo.CreateMessageWithAttachments(ctx, chat.ID, user.ID, "", "ordered", []string{first.ID, second.ID})
|
||||
if err != nil || replay.ID != sent.ID {
|
||||
t.Fatalf("historical replay changed after missing: %v", err)
|
||||
}
|
||||
repeated, err := service.Reconcile(ctx, true, 90*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if repeated.Deleted != 0 || repeated.MarkedFailed != 0 || repeated.Orphans != 0 || repeated.Missing != 0 {
|
||||
t.Fatalf("not repeatable %+v", repeated)
|
||||
}
|
||||
t.Logf("dry-run=%+v apply=%+v repeat=%+v; fresh, locked and referenced objects retained", dry, applied, repeated)
|
||||
}
|
||||
|
||||
func TestS3WireFixture(t *testing.T) {
|
||||
fake := &fakeS3{objects: map[string]fakeObject{}}
|
||||
server := httptest.NewServer(fake)
|
||||
defer server.Close()
|
||||
client, err := minio.New(strings.TrimPrefix(server.URL, "http://"), &minio.Options{Creds: credentials.NewStaticV4("test-key", "test-secret", ""), Region: "us-east-1", MaxRetries: 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload := []byte("exact object bytes")
|
||||
_, err = client.PutObject(context.Background(), "attachments", "original/test", bytes.NewReader(payload), int64(len(payload)), minio.PutObjectOptions{ContentType: "image/png", DisableMultipart: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
obj, err := client.GetObject(context.Background(), "attachments", "original/test", minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer obj.Close()
|
||||
got, err := io.ReadAll(obj)
|
||||
if err != nil || !bytes.Equal(got, payload) {
|
||||
t.Fatalf("wire fixture did not store original: %q %v", got, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"slices"
|
||||
)
|
||||
|
||||
func (s *Storage) CreateMessage(ctx context.Context, chatID, senderID, text, key string) (domain.Message, error) {
|
||||
return s.CreateMessageWithAttachments(ctx, chatID, senderID, text, key, nil)
|
||||
}
|
||||
|
||||
func (s *Storage) CreateMessageWithAttachments(ctx context.Context, chatID, senderID, text, key string, ids []string) (domain.Message, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
if ids == nil {
|
||||
ids = []string{}
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return domain.Message{}, dbError(err)
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
// Serialize this idempotency scope before validating attachments. A replay remains a
|
||||
// replay even when reconciliation has since marked an original as missing.
|
||||
if key != "" {
|
||||
_, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, senderID+":"+chatID+":"+key)
|
||||
if err != nil {
|
||||
return domain.Message{}, dbError(err)
|
||||
}
|
||||
old := domain.Message{ChatID: chatID, SenderID: senderID}
|
||||
err = tx.QueryRow(ctx, `SELECT id::text,text,attachment_ids::text[],created_at FROM messages WHERE sender_id=$1 AND chat_id=$2 AND idempotency_key=$3`, senderID, chatID, key).Scan(&old.ID, &old.Text, &old.AttachmentIDs, &old.CreatedAt)
|
||||
if err == nil {
|
||||
if old.Text != text || !slices.Equal(old.AttachmentIDs, ids) {
|
||||
return domain.Message{}, domain.NewApplicationError(domain.ErrorConflict, "Idempotency-Key уже использован с другим телом")
|
||||
}
|
||||
return old, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Message{}, dbError(err)
|
||||
}
|
||||
}
|
||||
// Lock each metadata row against reconciler updates until the link is committed.
|
||||
for _, id := range ids {
|
||||
var status string
|
||||
err = tx.QueryRow(ctx, `SELECT status FROM attachments WHERE id=$1 AND chat_id=$2 FOR SHARE`, id, chatID).Scan(&status)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Message{}, domain.NewApplicationError(domain.ErrorNotFound, "Объект не найден")
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Message{}, dbError(err)
|
||||
}
|
||||
if status != "ready" {
|
||||
return domain.Message{}, domain.NewApplicationError(domain.ErrorConflict, "Вложение не готово")
|
||||
}
|
||||
}
|
||||
m := domain.Message{ID: uuid.NewString(), ChatID: chatID, SenderID: senderID, Text: text, AttachmentIDs: ids}
|
||||
var storedKey *string
|
||||
if key != "" {
|
||||
storedKey = &key
|
||||
}
|
||||
err = tx.QueryRow(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,idempotency_key,attachment_ids) VALUES($1,$2,$3,$4,$5,$6) RETURNING created_at`, m.ID, chatID, senderID, text, storedKey, ids).Scan(&m.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Message{}, dbError(err)
|
||||
}
|
||||
return m, dbError(tx.Commit(ctx))
|
||||
}
|
||||
|
||||
func (s *Storage) ListMessages(ctx context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
query := `SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.attachment_ids::text[],m.created_at FROM messages m WHERE m.chat_id=$1`
|
||||
args := []any{chatID, limit}
|
||||
if after != nil {
|
||||
query += ` AND (m.created_at,m.id)>($3,$4)`
|
||||
args = append(args, after.CreatedAt, after.ID)
|
||||
}
|
||||
query += ` ORDER BY m.created_at,m.id LIMIT $2`
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []domain.Message{}
|
||||
for rows.Next() {
|
||||
var m domain.Message
|
||||
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.AttachmentIDs, &m.CreatedAt); err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
result = append(result, m)
|
||||
}
|
||||
return result, dbError(rows.Err())
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
|
||||
)
|
||||
|
||||
type Storage struct {
|
||||
pool *pgxpool.Pool
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
var _ chatusecase.Repository = (*Storage)(nil)
|
||||
|
||||
func New(pool *pgxpool.Pool, timeout time.Duration) *Storage {
|
||||
return &Storage{pool: pool, timeout: timeout}
|
||||
}
|
||||
|
||||
func (s *Storage) Ready(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
return dbError(s.pool.Ping(ctx))
|
||||
}
|
||||
|
||||
func dbError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case "23505":
|
||||
return chatusecase.ErrUsernameTaken
|
||||
case "23503":
|
||||
return chatusecase.ErrUserNotFound
|
||||
}
|
||||
log.Printf("postgres operation failed: sqlstate=%s", pgErr.Code)
|
||||
} else if !errors.Is(err, pgx.ErrNoRows) {
|
||||
log.Print("postgres operation failed")
|
||||
}
|
||||
return domain.NewApplicationError(domain.ErrorUnavailable, "Хранилище недоступно")
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres"
|
||||
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
|
||||
)
|
||||
|
||||
func TestIntegration(t *testing.T) {
|
||||
if os.Getenv("INTEGRATION_TESTS") != "1" {
|
||||
t.Skip("run make test-integration against the Compose stack")
|
||||
}
|
||||
ctx := context.Background()
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pc, err := pgxpool.ParseConfig("sslmode=disable")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pc.ConnConfig.Host = cfg.PostgresHost
|
||||
pc.ConnConfig.Port = cfg.PostgresPort
|
||||
pc.ConnConfig.User = cfg.PostgresUser
|
||||
pc.ConnConfig.Database = cfg.PostgresDatabase
|
||||
pc.ConnConfig.Password = cfg.PostgresPassword
|
||||
pc.ConnConfig.RuntimeParams["timezone"] = "UTC"
|
||||
pc.MaxConns = 4
|
||||
admin, err := pgxpool.NewWithConfig(ctx, pc.Copy())
|
||||
if err != nil {
|
||||
t.Fatal("connect failed")
|
||||
}
|
||||
defer admin.Close()
|
||||
// Identifier is generated by the test, never from an API request.
|
||||
schema := "test_" + uuid.New().String()[:8]
|
||||
if _, err = admin.Exec(ctx, `CREATE SCHEMA `+schema); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer admin.Exec(ctx, `DROP SCHEMA `+schema+` CASCADE`)
|
||||
pc.ConnConfig.RuntimeParams["search_path"] = schema
|
||||
pool, err := pgxpool.NewWithConfig(ctx, pc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
runGoose := func(t *testing.T, command string) {
|
||||
t.Helper()
|
||||
migrationDir := os.Getenv("GOOSE_MIGRATION_DIR")
|
||||
if migrationDir == "" {
|
||||
migrationDir, err = filepath.Abs("../../../../migrations")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
connection := url.URL{Scheme: "postgres", User: url.User(cfg.PostgresUser), Host: net.JoinHostPort(cfg.PostgresHost, strconv.Itoa(int(cfg.PostgresPort))), Path: cfg.PostgresDatabase}
|
||||
connection.RawQuery = url.Values{"sslmode": {"disable"}, "search_path": {schema}, "connect_timeout": {"5"}}.Encode()
|
||||
commandCtx, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||
defer cancel()
|
||||
commandExec := exec.CommandContext(commandCtx, "goose", "-env", "/dev/null", "-dir", migrationDir, "-timeout", "30s", command)
|
||||
commandExec.Env = append(os.Environ(), "GOOSE_DRIVER=postgres", "GOOSE_DBSTRING="+connection.String(), "PGPASSWORD="+cfg.PostgresPassword)
|
||||
output, err := commandExec.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("goose %s: %v: %s", command, err, strings.ReplaceAll(string(output), cfg.PostgresPassword, "[redacted]"))
|
||||
}
|
||||
t.Logf("goose %s: %s", command, output)
|
||||
}
|
||||
runGoose(t, "up")
|
||||
runGoose(t, "up")
|
||||
var versions int
|
||||
if err = pool.QueryRow(ctx, `SELECT count(*) FROM goose_db_version WHERE version_id=1 AND is_applied`).Scan(&versions); err != nil || versions != 1 {
|
||||
t.Fatalf("migration versions=%d error=%v", versions, err)
|
||||
}
|
||||
repo := postgres.New(pool, 2*time.Second)
|
||||
t.Run("registration_race", func(t *testing.T) {
|
||||
const count = 12
|
||||
results := make(chan error, count)
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for i := 0; i < count; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
_, err := repo.CreateUser(ctx, "same_username", "Same", "test-hash")
|
||||
results <- err
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
successes, conflicts := 0, 0
|
||||
for err := range results {
|
||||
if err == nil {
|
||||
successes++
|
||||
} else if errors.Is(err, chatusecase.ErrUsernameTaken) {
|
||||
conflicts++
|
||||
} else {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if successes != 1 || conflicts != count-1 {
|
||||
t.Fatalf("successes=%d conflicts=%d", successes, conflicts)
|
||||
}
|
||||
t.Logf("12 concurrent INSERTs: %d success, %d unique conflicts", successes, conflicts)
|
||||
})
|
||||
user, err := repo.CreateUser(ctx, "history_owner", "Owner", "test-hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Run("rollback", func(t *testing.T) {
|
||||
_, err := repo.CreateChat(ctx, "must rollback", []string{user.ID, uuid.NewString()})
|
||||
if !errors.Is(err, chatusecase.ErrUserNotFound) {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
var chats, members int
|
||||
if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM chats),(SELECT count(*) FROM chat_members)`).Scan(&chats, &members); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if chats != 0 || members != 0 {
|
||||
t.Fatalf("partial transaction: chats=%d members=%d", chats, members)
|
||||
}
|
||||
t.Log("failed second member INSERT left 0 chats and 0 members")
|
||||
})
|
||||
chat, err := repo.CreateChat(ctx, "History", []string{user.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Run("lab4_attachments_and_reconciliation", func(t *testing.T) {
|
||||
isolated, e := repo.CreateChat(ctx, "Lab4", []string{user.ID})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
lab4Backend(t, pool, repo, user, isolated)
|
||||
})
|
||||
_, err = pool.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||
SELECT md5(i::text)::uuid,$1,$2,'synthetic message '||i,
|
||||
timestamptz '2026-01-01 00:00:00+00' + (i / 10) * interval '1 millisecond'
|
||||
FROM generate_series(1,10000) i`, chat.ID, user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `ANALYZE messages`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Run("keyset_and_explain", func(t *testing.T) {
|
||||
seen := make(map[string]bool)
|
||||
var after *domain.Position
|
||||
for {
|
||||
page, err := repo.ListMessages(ctx, chat.ID, after, 97)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page) == 0 {
|
||||
break
|
||||
}
|
||||
for _, message := range page {
|
||||
if seen[message.ID] {
|
||||
t.Fatal("duplicate on page boundary")
|
||||
}
|
||||
seen[message.ID] = true
|
||||
}
|
||||
last := page[len(page)-1]
|
||||
after = &domain.Position{CreatedAt: last.CreatedAt, ID: last.ID}
|
||||
}
|
||||
if len(seen) != 10000 {
|
||||
t.Fatalf("history count=%d", len(seen))
|
||||
}
|
||||
rows, err := pool.Query(ctx, `EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.created_at FROM messages m
|
||||
WHERE m.chat_id=$1 AND (m.created_at,m.id)>($2,$3) ORDER BY m.created_at,m.id LIMIT $4`,
|
||||
chat.ID, time.Date(2026, 1, 1, 0, 0, 0, 900000000, time.UTC), "00000000-0000-0000-0000-000000000000", 51)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
t.Log("EXPLAIN on 10,000 messages, cursor near the end (9,000):")
|
||||
for rows.Next() {
|
||||
var line string
|
||||
if err = rows.Scan(&line); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log(line)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log("keyset traversal returned 10,000 distinct messages, including equal timestamps")
|
||||
})
|
||||
t.Run("idempotency_race", func(t *testing.T) {
|
||||
isolated, err := repo.CreateChat(ctx, "Idempotency", []string{user.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const count = 16
|
||||
results := make(chan domain.Message, count)
|
||||
failures := make(chan error, count)
|
||||
start := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < count; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
message, err := repo.CreateMessage(ctx, isolated.ID, user.ID, "exactly once", "shared-key")
|
||||
if err != nil {
|
||||
failures <- err
|
||||
return
|
||||
}
|
||||
results <- message
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
close(failures)
|
||||
for err := range failures {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var first domain.Message
|
||||
for message := range results {
|
||||
if first.ID == "" {
|
||||
first = message
|
||||
}
|
||||
if message.ID != first.ID || !message.CreatedAt.Equal(first.CreatedAt) || message.Text != first.Text {
|
||||
t.Fatal("concurrent replay changed result")
|
||||
}
|
||||
}
|
||||
var rows int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM messages WHERE chat_id=$1`, isolated.ID).Scan(&rows); err != nil || rows != 1 {
|
||||
t.Fatalf("expected one durable effect, got %d: %v", rows, err)
|
||||
}
|
||||
_, err = repo.CreateMessage(ctx, isolated.ID, user.ID, "different", "shared-key")
|
||||
applicationError, ok := domain.AsApplicationError(err)
|
||||
if !ok || applicationError.Code != domain.ErrorConflict {
|
||||
t.Fatalf("expected conflict, got %v", err)
|
||||
}
|
||||
t.Log("16 concurrent PostgreSQL requests: one effect, identical replay, changed body conflicts")
|
||||
})
|
||||
t.Run("goose_legacy_and_down", func(t *testing.T) {
|
||||
// This is the disposable test schema, never the application's public schema.
|
||||
const digestSQL = `SELECT md5(string_agg(ROW(id,chat_id,sender_id,text,created_at)::text,',' ORDER BY id)) FROM messages`
|
||||
var before, after string
|
||||
if err = pool.QueryRow(ctx, digestSQL).Scan(&before); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `DROP TABLE goose_db_version;
|
||||
CREATE TABLE schema_migrations(version text PRIMARY KEY,applied_at timestamptz NOT NULL DEFAULT now());
|
||||
INSERT INTO schema_migrations(version) VALUES('001_initial.sql')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGoose(t, "up")
|
||||
runGoose(t, "up")
|
||||
if err = pool.QueryRow(ctx, digestSQL).Scan(&after); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if before != after {
|
||||
t.Fatal("legacy migration changed message data")
|
||||
}
|
||||
t.Log("adopted legacy schema: all existing messages are unchanged")
|
||||
runGoose(t, "reset")
|
||||
var tables int
|
||||
if err = pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_schema=$1 AND table_name IN ('users','chats','chat_members','messages','schema_migrations')`, schema).Scan(&tables); err != nil || tables != 0 {
|
||||
t.Fatalf("down left %d application tables: %v", tables, err)
|
||||
}
|
||||
runGoose(t, "up")
|
||||
if err = pool.QueryRow(ctx, `SELECT count(*) FROM messages`).Scan(&tables); err != nil || tables != 0 {
|
||||
t.Fatalf("up after down failed: %v", err)
|
||||
}
|
||||
t.Log("down and up succeeded in isolated schema")
|
||||
})
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (s *Storage) CreateUser(ctx context.Context, username, displayName, hash string) (domain.User, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var user domain.User
|
||||
err := s.pool.QueryRow(ctx, `INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)
|
||||
RETURNING id::text,username,display_name,created_at`, uuid.NewString(), username, displayName, hash).
|
||||
Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
return user, dbError(err)
|
||||
}
|
||||
|
||||
func (s *Storage) User(ctx context.Context, id string) (domain.User, bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var user domain.User
|
||||
err := s.pool.QueryRow(ctx, `SELECT id::text,username,display_name,created_at FROM users WHERE id=$1`, id).
|
||||
Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return user, false, nil
|
||||
}
|
||||
return user, err == nil, dbError(err)
|
||||
}
|
||||
|
||||
func (s *Storage) UserByUsername(ctx context.Context, username string) (domain.User, string, bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var user domain.User
|
||||
var hash string
|
||||
err := s.pool.QueryRow(ctx, `SELECT id::text,username,display_name,created_at,password_hash FROM users WHERE username=$1`, username).
|
||||
Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return user, "", false, nil
|
||||
}
|
||||
return user, hash, err == nil, dbError(err)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
type Redis struct {
|
||||
client *redis.Client
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func NewRedis(client *redis.Client, timeout time.Duration) *Redis {
|
||||
return &Redis{client: client, timeout: timeout}
|
||||
}
|
||||
|
||||
func unavailable(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
log.Print("redis operation failed")
|
||||
return domain.NewApplicationError(domain.ErrorUnavailable, "Хранилище сессий недоступно")
|
||||
}
|
||||
|
||||
func (s *Redis) Ready(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
return unavailable(s.client.Ping(ctx).Err())
|
||||
}
|
||||
|
||||
func (s *Redis) Put(ctx context.Context, key string, value domain.Session) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Absolute expiry prevents TTL extension by network delay or restart.
|
||||
return unavailable(s.client.Do(ctx, "SET", "session:"+key, data, "PXAT", value.ExpiresAt.UnixMilli()).Err())
|
||||
}
|
||||
|
||||
func (s *Redis) Get(ctx context.Context, key string) (domain.Session, bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var value domain.Session
|
||||
data, err := s.client.Get(ctx, "session:"+key).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return value, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return value, false, unavailable(err)
|
||||
}
|
||||
if err = json.Unmarshal(data, &value); err != nil {
|
||||
return value, false, unavailable(err)
|
||||
}
|
||||
return value, time.Now().Before(value.ExpiresAt), nil
|
||||
}
|
||||
|
||||
func (s *Redis) Delete(ctx context.Context, key string) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
count, err := s.client.Del(ctx, "session:"+key).Result()
|
||||
return count > 0, unavailable(err)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUsernameTaken = errors.New("username is already taken")
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
ErrChatNotFound = errors.New("chat not found")
|
||||
ErrNotMember = errors.New("user is not a chat member")
|
||||
)
|
||||
|
||||
// Repository is the persistence port required by the chat use case.
|
||||
type Repository interface {
|
||||
Ready(ctx context.Context) error
|
||||
UserByUsername(ctx context.Context, username string) (domain.User, string, bool, error)
|
||||
CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error)
|
||||
User(ctx context.Context, id string) (domain.User, bool, error)
|
||||
CreateChat(ctx context.Context, title string, memberIDs []string) (domain.Chat, error)
|
||||
ChatForUser(ctx context.Context, chatID, userID string) (domain.Chat, error)
|
||||
ListChats(ctx context.Context, userID string, after *domain.Position, limit int) ([]domain.Chat, error)
|
||||
CreateMessage(ctx context.Context, chatID, senderID, text, key string) (domain.Message, error)
|
||||
ListMessages(ctx context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error)
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
|
||||
)
|
||||
|
||||
type UseCase struct {
|
||||
repository Repository
|
||||
sessions Sessions
|
||||
sessionTTL time.Duration
|
||||
}
|
||||
|
||||
func New(repository Repository, sessions Sessions, ttl time.Duration) *UseCase {
|
||||
return &UseCase{repository: repository, sessions: sessions, sessionTTL: ttl}
|
||||
}
|
||||
|
||||
func (u *UseCase) CreateUser(ctx context.Context, user domain.User, secret string) (domain.User, error) {
|
||||
if !validUsername(user.Username) {
|
||||
return domain.User{}, invalid("username должен соответствовать [a-z0-9_]{3,32}")
|
||||
}
|
||||
if !validRequiredText(user.DisplayName, 100) {
|
||||
return domain.User{}, invalid("display_name должен содержать от 1 до 100 символов")
|
||||
}
|
||||
if !validPassword(secret) {
|
||||
return domain.User{}, invalid("password должен содержать от 12 до 128 символов")
|
||||
}
|
||||
hash, err := password.Hash(ctx, secret)
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
created, err := u.repository.CreateUser(ctx, user.Username, user.DisplayName, hash)
|
||||
if errors.Is(err, ErrUsernameTaken) {
|
||||
return domain.User{}, domain.NewApplicationError(domain.ErrorConflict, "Пользователь с таким username уже существует")
|
||||
}
|
||||
return created, err
|
||||
}
|
||||
|
||||
func (u *UseCase) CreateChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error) {
|
||||
if !validRequiredText(chat.Title, 100) {
|
||||
return domain.Chat{}, invalid("title должен содержать от 1 до 100 символов")
|
||||
}
|
||||
if len(chat.MemberIDs) < 1 || len(chat.MemberIDs) > 100 {
|
||||
return domain.Chat{}, invalid("member_ids должен содержать от 1 до 100 участников")
|
||||
}
|
||||
|
||||
normalizedIDs := make([]string, len(chat.MemberIDs))
|
||||
seen := make(map[string]struct{}, len(chat.MemberIDs))
|
||||
callerIncluded := false
|
||||
for index, memberID := range chat.MemberIDs {
|
||||
normalized, valid := normalizeUUID(memberID)
|
||||
if !valid {
|
||||
return domain.Chat{}, invalid("member_ids содержит некорректный UUID")
|
||||
}
|
||||
if _, duplicate := seen[normalized]; duplicate {
|
||||
return domain.Chat{}, invalid("member_ids содержит повторяющиеся UUID")
|
||||
}
|
||||
normalizedIDs[index] = normalized
|
||||
seen[normalized] = struct{}{}
|
||||
callerIncluded = callerIncluded || normalized == callerID
|
||||
}
|
||||
if !callerIncluded {
|
||||
return domain.Chat{}, invalid("текущий пользователь должен входить в member_ids")
|
||||
}
|
||||
|
||||
created, err := u.repository.CreateChat(ctx, chat.Title, normalizedIDs)
|
||||
if errors.Is(err, ErrUserNotFound) {
|
||||
return domain.Chat{}, invalid("member_ids содержит неизвестного пользователя")
|
||||
}
|
||||
return created, err
|
||||
}
|
||||
|
||||
func (u *UseCase) GetChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error) {
|
||||
chatID, valid := normalizeUUID(chat.ID)
|
||||
if !valid {
|
||||
return domain.Chat{}, invalid("Некорректный chat_id")
|
||||
}
|
||||
return u.chatForUser(ctx, chatID, callerID)
|
||||
}
|
||||
|
||||
func (u *UseCase) ListChats(ctx context.Context, callerID string, pagination domain.Pagination) (domain.ChatPage, error) {
|
||||
if pagination.Limit < 1 || pagination.Limit > 100 {
|
||||
return domain.ChatPage{}, invalid("limit должен быть целым числом от 1 до 100")
|
||||
}
|
||||
items, err := u.repository.ListChats(ctx, callerID, pagination.After, pagination.Limit+1)
|
||||
if err != nil {
|
||||
return domain.ChatPage{}, err
|
||||
}
|
||||
page := domain.ChatPage{Items: items, HasMore: len(items) > pagination.Limit}
|
||||
if page.HasMore {
|
||||
page.Items = page.Items[:pagination.Limit]
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (u *UseCase) CreateMessage(ctx context.Context, callerID string, message domain.Message) (domain.Message, error) {
|
||||
chatID, valid := normalizeUUID(message.ChatID)
|
||||
if !valid {
|
||||
return domain.Message{}, invalid("Некорректный chat_id")
|
||||
}
|
||||
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if !utf8.ValidString(message.Text) || utf8.RuneCountInString(message.Text) > 4000 || (strings.TrimSpace(message.Text) == "" && len(message.AttachmentIDs) == 0) {
|
||||
return domain.Message{}, invalid("text должен содержать от 1 до 4000 символов")
|
||||
}
|
||||
if len(message.AttachmentIDs) > 10 {
|
||||
return domain.Message{}, invalid("Не более 10 вложений")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for i, id := range message.AttachmentIDs {
|
||||
normalized, ok := normalizeUUID(id)
|
||||
if !ok || seen[normalized] {
|
||||
return domain.Message{}, invalid("Некорректные или повторные attachment_ids")
|
||||
}
|
||||
seen[normalized] = true
|
||||
message.AttachmentIDs[i] = normalized
|
||||
}
|
||||
var created domain.Message
|
||||
var err error
|
||||
if repository, ok := u.repository.(interface {
|
||||
CreateMessageWithAttachments(context.Context, string, string, string, string, []string) (domain.Message, error)
|
||||
}); ok {
|
||||
created, err = repository.CreateMessageWithAttachments(ctx, chatID, callerID, message.Text, message.IdempotencyKey, message.AttachmentIDs)
|
||||
} else if len(message.AttachmentIDs) > 0 {
|
||||
return domain.Message{}, notFound()
|
||||
} else {
|
||||
created, err = u.repository.CreateMessage(ctx, chatID, callerID, message.Text, message.IdempotencyKey)
|
||||
}
|
||||
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
|
||||
return domain.Message{}, notFound()
|
||||
}
|
||||
return created, err
|
||||
}
|
||||
|
||||
func (u *UseCase) ListMessages(ctx context.Context, callerID string, chat domain.Chat, pagination domain.Pagination) (domain.MessagePage, error) {
|
||||
chatID, valid := normalizeUUID(chat.ID)
|
||||
if !valid {
|
||||
return domain.MessagePage{}, invalid("Некорректный chat_id")
|
||||
}
|
||||
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
|
||||
return domain.MessagePage{}, err
|
||||
}
|
||||
if pagination.Limit < 1 || pagination.Limit > 100 {
|
||||
return domain.MessagePage{}, invalid("limit должен быть целым числом от 1 до 100")
|
||||
}
|
||||
items, err := u.repository.ListMessages(ctx, chatID, pagination.After, pagination.Limit+1)
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, err
|
||||
}
|
||||
page := domain.MessagePage{Items: items, HasMore: len(items) > pagination.Limit}
|
||||
if page.HasMore {
|
||||
page.Items = page.Items[:pagination.Limit]
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (u *UseCase) chatForUser(ctx context.Context, chatID, callerID string) (domain.Chat, error) {
|
||||
chat, err := u.repository.ChatForUser(ctx, chatID, callerID)
|
||||
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
|
||||
return domain.Chat{}, notFound()
|
||||
}
|
||||
return chat, err
|
||||
}
|
||||
|
||||
func invalid(message string) error {
|
||||
return domain.NewApplicationError(domain.ErrorInvalid, message)
|
||||
}
|
||||
|
||||
func unauthorized() error {
|
||||
return domain.NewApplicationError(domain.ErrorUnauthorized, "Требуется действительная сессия")
|
||||
}
|
||||
|
||||
func notFound() error {
|
||||
return domain.NewApplicationError(domain.ErrorNotFound, "Объект не найден")
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
|
||||
)
|
||||
|
||||
type Sessions interface {
|
||||
Put(context.Context, string, domain.Session) error
|
||||
Get(context.Context, string) (domain.Session, bool, error)
|
||||
Delete(context.Context, string) (bool, error)
|
||||
Ready(context.Context) error
|
||||
}
|
||||
|
||||
func validPassword(value string) bool {
|
||||
n := utf8.RuneCountInString(value)
|
||||
return utf8.ValidString(value) && n >= 12 && n <= 128 && strings.TrimSpace(value) != ""
|
||||
}
|
||||
|
||||
func tokenKey(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (u *UseCase) Authenticate(ctx context.Context, token string) (domain.User, error) {
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(token)
|
||||
if err != nil || len(decoded) != 32 {
|
||||
return domain.User{}, unauthorized()
|
||||
}
|
||||
session, exists, err := u.sessions.Get(ctx, tokenKey(token))
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if !exists || !time.Now().Before(session.ExpiresAt) {
|
||||
return domain.User{}, unauthorized()
|
||||
}
|
||||
user, exists, err := u.repository.User(ctx, session.UserID)
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if !exists {
|
||||
return domain.User{}, unauthorized()
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (u *UseCase) CreateSession(ctx context.Context, username, secret string) (domain.Login, error) {
|
||||
if !validUsername(username) || !validPassword(secret) {
|
||||
return domain.Login{}, unauthorized()
|
||||
}
|
||||
user, hash, exists, err := u.repository.UserByUsername(ctx, username)
|
||||
if err != nil {
|
||||
return domain.Login{}, err
|
||||
}
|
||||
if !exists {
|
||||
hash = password.DummyHash
|
||||
}
|
||||
valid, err := password.Verify(ctx, secret, hash)
|
||||
if err != nil {
|
||||
return domain.Login{}, err
|
||||
}
|
||||
if !valid || !exists {
|
||||
return domain.Login{}, unauthorized()
|
||||
}
|
||||
var raw [32]byte
|
||||
if _, err = rand.Read(raw[:]); err != nil {
|
||||
return domain.Login{}, err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw[:])
|
||||
expires := time.Now().UTC().Add(u.sessionTTL)
|
||||
if err = u.sessions.Put(ctx, tokenKey(token), domain.Session{UserID: user.ID, ExpiresAt: expires}); err != nil {
|
||||
return domain.Login{}, err
|
||||
}
|
||||
return domain.Login{Token: token, ExpiresAt: expires, User: user}, nil
|
||||
}
|
||||
|
||||
func (u *UseCase) DeleteSession(ctx context.Context, token string) error {
|
||||
deleted, err := u.sessions.Delete(ctx, tokenKey(token))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !deleted {
|
||||
return unauthorized()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *UseCase) Ready(ctx context.Context) error {
|
||||
if err := u.repository.Ready(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return u.sessions.Ready(ctx)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPasswordContract(t *testing.T) {
|
||||
for _, value := range []string{"", "too-short", strings.Repeat(" ", 12), strings.Repeat("x", 129), strings.Repeat("x", 12) + string([]byte{0xff})} {
|
||||
if validPassword(value) {
|
||||
t.Fatal("invalid password accepted")
|
||||
}
|
||||
}
|
||||
for _, value := range []string{strings.Repeat("🔑", 128), "valid:password", " password with spaces "} {
|
||||
if !validPassword(value) {
|
||||
t.Fatal("valid Unicode password rejected")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func normalizeUUID(value string) (string, bool) {
|
||||
parsed, err := uuid.Parse(value)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
normalized := parsed.String()
|
||||
if !strings.EqualFold(value, normalized) {
|
||||
return "", false
|
||||
}
|
||||
return normalized, true
|
||||
}
|
||||
|
||||
func validUsername(value string) bool {
|
||||
if len(value) < 3 || len(value) > 32 {
|
||||
return false
|
||||
}
|
||||
for _, char := range value {
|
||||
if char != '_' && (char < 'a' || char > 'z') && (char < '0' || char > '9') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func validRequiredText(value string, maxRunes int) bool {
|
||||
length := utf8.RuneCountInString(value)
|
||||
return utf8.ValidString(value) && length >= 1 && length <= maxRunes && strings.TrimSpace(value) != ""
|
||||
}
|
||||
Reference in New Issue
Block a user