forked from mtusi2026/mtusi2026lab5
ЛР 5: асинхронная обработка изображений, уровень 5
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
)
|
||||
|
||||
// routeUploadAttachment освобождён от общего лимита тела: свой лимит применяется в сервисе, после
|
||||
// аутентификации и проверки доступа.
|
||||
const routeUploadAttachment = "/api/v1/chats/:chat_id/attachments"
|
||||
|
||||
// transferTimeout — предел на передачу одного файла. Общие таймауты сервера (10 с) рассчитаны на
|
||||
// JSON и оборвали бы загрузку 10 МиБ на медленном канале. Предел обязателен: иначе медленный клиент
|
||||
// занимал бы слот загрузки неограниченно долго.
|
||||
const transferTimeout = 60 * time.Second
|
||||
|
||||
type attachmentsHandler struct {
|
||||
attachments service.AttachmentsService
|
||||
}
|
||||
|
||||
// rejectedBodyDrainLimit — сколько байт отклонённой загрузки дочитывается впустую. Клиент обычно
|
||||
// сначала отправляет всё тело и только потом читает ответ: если перестать читать, он зависнет и
|
||||
// вместо 413 получит обрыв. Дочитывание идёт в никуда, поэтому память не расходует, а его время
|
||||
// ограничено transferTimeout. Тело больше этого предела приводит к закрытию соединения.
|
||||
const rejectedBodyDrainLimit = 64 << 20
|
||||
|
||||
func extendDeadlines(c echo.Context) {
|
||||
rc := http.NewResponseController(c.Response())
|
||||
deadline := time.Now().Add(transferTimeout)
|
||||
// Ошибка значит, что соединение не поддерживает дедлайны: тогда действуют общие таймауты.
|
||||
_ = rc.SetReadDeadline(deadline)
|
||||
_ = rc.SetWriteDeadline(deadline)
|
||||
}
|
||||
|
||||
// uploadTransfer стоит снаружи аутентификации, поэтому покрывает и отказы 401. Небольшой ответ об
|
||||
// ошибке остаётся в буфере сервера и уходит клиенту после дочитывания.
|
||||
func uploadTransfer(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
extendDeadlines(c)
|
||||
err := next(c)
|
||||
_, _ = io.CopyN(io.Discard, c.Request().Body, rejectedBodyDrainLimit)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (h *attachmentsHandler) upload(c echo.Context) error {
|
||||
req := c.Request()
|
||||
// Несколько filename неоднозначны: пустое значение сервис отклонит как неверное имя.
|
||||
var filename string
|
||||
if values := c.QueryParams()["filename"]; len(values) == 1 {
|
||||
filename = values[0]
|
||||
}
|
||||
att, err := h.attachments.Upload(req.Context(), service.UploadInput{
|
||||
CallerID: c.Get(middleware.AuthUserIDKey).(string),
|
||||
ChatID: c.Param("chat_id"),
|
||||
Filename: filename,
|
||||
ContentType: req.Header.Get(echo.HeaderContentType),
|
||||
ContentLength: req.ContentLength,
|
||||
Body: req.Body,
|
||||
})
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusAccepted, toAttachmentResponse(att))
|
||||
}
|
||||
|
||||
func (h *attachmentsHandler) get(c echo.Context) error {
|
||||
att, err := h.attachments.Get(c.Request().Context(), c.Get(middleware.AuthUserIDKey).(string), c.Param("attachment_id"))
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, toAttachmentResponse(att))
|
||||
}
|
||||
|
||||
func (h *attachmentsHandler) content(c echo.Context) error {
|
||||
extendDeadlines(c)
|
||||
variant := service.VariantOriginal
|
||||
if values, ok := c.QueryParams()["variant"]; ok {
|
||||
variant = values[0]
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(c.Request().Context(), transferTimeout)
|
||||
defer cancel()
|
||||
|
||||
att, body, err := h.attachments.Content(ctx, c.Get(middleware.AuthUserIDKey).(string), c.Param("attachment_id"), variant)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
defer body.Close()
|
||||
|
||||
header := c.Response().Header()
|
||||
header.Set(echo.HeaderContentLength, strconv.FormatInt(att.SizeBytes, 10))
|
||||
// Файл загрузил пользователь: браузер не должен угадывать тип или показывать его как страницу.
|
||||
header.Set("X-Content-Type-Options", "nosniff")
|
||||
header.Set("Cache-Control", "private, no-store")
|
||||
if cd := mime.FormatMediaType("attachment", map[string]string{"filename": att.Filename}); cd != "" {
|
||||
header.Set(echo.HeaderContentDisposition, cd)
|
||||
} else {
|
||||
header.Set(echo.HeaderContentDisposition, "attachment")
|
||||
}
|
||||
// Обрыв после начала передачи клиент увидит как неполный ответ: длина объявлена заранее.
|
||||
return c.Stream(http.StatusOK, att.ContentType, body)
|
||||
}
|
||||
|
||||
func toAttachmentResponse(a domain.Attachment) dto.AttachmentResponse {
|
||||
return dto.AttachmentResponse{
|
||||
ID: a.ID,
|
||||
ChatID: a.ChatID,
|
||||
OwnerID: a.OwnerID,
|
||||
Filename: a.Filename,
|
||||
ContentType: a.ContentType,
|
||||
SizeBytes: a.SizeBytes,
|
||||
SHA256: a.SHA256,
|
||||
Status: a.Status,
|
||||
Variants: attachmentVariants(a),
|
||||
ErrorCode: a.ErrorCode,
|
||||
CreatedAt: dto.NewTimestamp(a.CreatedAt),
|
||||
UpdatedAt: dto.NewTimestamp(a.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func attachmentVariants(a domain.Attachment) []dto.VariantResponse {
|
||||
v := []dto.VariantResponse{}
|
||||
if a.Status == domain.StatusReady {
|
||||
for _, t := range a.Variants {
|
||||
v = append(v, dto.VariantResponse{Name: t.Name, ContentType: t.ContentType, SizeBytes: t.SizeBytes, Width: t.Width, Height: t.Height, SHA256: t.SHA256})
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
type authHandler struct {
|
||||
auth service.AuthService
|
||||
}
|
||||
|
||||
func (h *authHandler) createSession(c echo.Context) error {
|
||||
if c.Request().ContentLength > 0 {
|
||||
return WriteError(c, &validate.Error{Field: "body", Reason: "must be empty, credentials go in Authorization: Basic"})
|
||||
}
|
||||
username, password, ok := parseBasic(c.Request().Header.Get(echo.HeaderAuthorization))
|
||||
if !ok {
|
||||
return middleware.Unauthorized(c, middleware.BasicChallenge, "Invalid credentials")
|
||||
}
|
||||
|
||||
s, err := h.auth.Login(c.Request().Context(), username, password)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrUnauthorized) {
|
||||
return middleware.Unauthorized(c, middleware.BasicChallenge, "Invalid credentials")
|
||||
}
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, dto.SessionResponse{
|
||||
Token: s.Token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: dto.NewTimestamp(s.ExpiresAt),
|
||||
User: toUserResponse(s.User),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *authHandler) revokeSession(c echo.Context) error {
|
||||
tok := c.Get(middleware.AuthTokenKey).(string)
|
||||
if err := h.auth.Logout(c.Request().Context(), tok); err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.NoContent(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func parseBasic(header string) (username, password string, ok bool) {
|
||||
scheme, encoded, found := strings.Cut(header, " ")
|
||||
if !found || !strings.EqualFold(scheme, "Basic") {
|
||||
return "", "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(encoded))
|
||||
if err != nil || !utf8.Valid(raw) {
|
||||
return "", "", false
|
||||
}
|
||||
username, password, found = strings.Cut(string(raw), ":")
|
||||
if !found || username == "" || password == "" {
|
||||
return "", "", false
|
||||
}
|
||||
return username, password, true
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
type chatsHandler struct {
|
||||
chats service.ChatsService
|
||||
}
|
||||
|
||||
func (h *chatsHandler) create(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
var req dto.CreateChatRequest
|
||||
if err := decodeJSON(c.Request().Body, &req); err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
chat, err := h.chats.Create(c.Request().Context(), callerID, req.Title, req.MemberIDs)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, toChatResponse(chat))
|
||||
}
|
||||
|
||||
func (h *chatsHandler) get(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
chatID := c.Param("chat_id")
|
||||
|
||||
chat, err := h.chats.Get(c.Request().Context(), callerID, chatID)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, toChatResponse(chat))
|
||||
}
|
||||
|
||||
func (h *chatsHandler) list(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
limit, cursor, err := parsePageParams(c)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
page, err := h.chats.List(c.Request().Context(), callerID, cursor, limit)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, toChatsPage(page))
|
||||
}
|
||||
|
||||
func toChatResponse(ch domain.Chat) dto.ChatResponse {
|
||||
members := make([]string, len(ch.MemberIDs))
|
||||
copy(members, ch.MemberIDs)
|
||||
return dto.ChatResponse{
|
||||
ID: ch.ID,
|
||||
Title: ch.Title,
|
||||
MemberIDs: members,
|
||||
CreatedAt: dto.NewTimestamp(ch.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func toChatsPage(p domain.Page[domain.Chat]) dto.ChatsPageResponse {
|
||||
items := make([]dto.ChatResponse, 0, len(p.Items))
|
||||
for _, ch := range p.Items {
|
||||
items = append(items, toChatResponse(ch))
|
||||
}
|
||||
var next *string
|
||||
if p.NextCursor != "" {
|
||||
s := p.NextCursor
|
||||
next = &s
|
||||
}
|
||||
return dto.ChatsPageResponse{Items: items, NextCursor: next}
|
||||
}
|
||||
|
||||
func parsePageParams(c echo.Context) (int, string, error) {
|
||||
q := c.QueryParams()
|
||||
|
||||
limit := validate.LimitDefault
|
||||
if vals, ok := q["limit"]; ok {
|
||||
n, err := strconv.Atoi(vals[0])
|
||||
if err != nil {
|
||||
return 0, "", &validate.Error{Field: "limit", Reason: "must be an integer"}
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
|
||||
cursor := ""
|
||||
if vals, ok := q["cursor"]; ok {
|
||||
if vals[0] == "" {
|
||||
return 0, "", &validate.Error{Field: "cursor", Reason: "must not be empty"}
|
||||
}
|
||||
cursor = vals[0]
|
||||
}
|
||||
return limit, cursor, nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package dto
|
||||
|
||||
// VariantResponse — преобразованная копия. В lab4 вариантов нет, список всегда пуст.
|
||||
type VariantResponse struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
// AttachmentResponse намеренно не содержит object key: он внутренний.
|
||||
type AttachmentResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []VariantResponse `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
UpdatedAt Timestamp `json:"updated_at"`
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package dto
|
||||
|
||||
type CreateChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type ChatResponse struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
|
||||
type ChatsPageResponse struct {
|
||||
Items []ChatResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// AttachmentIDList — необязательное поле: отсутствие равно [], но явный null по контракту неверен.
|
||||
// Обычный срез принял бы null молча, поэтому разбор свой.
|
||||
type AttachmentIDList []string
|
||||
|
||||
func (l *AttachmentIDList) UnmarshalJSON(data []byte) error {
|
||||
if string(data) == "null" {
|
||||
return errors.New("attachment_ids must be an array")
|
||||
}
|
||||
return json.Unmarshal(data, (*[]string)(l))
|
||||
}
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
// Text — указатель: поле обязательно и при наличии вложений, а "" допустим только с ними.
|
||||
Text *string `json:"text"`
|
||||
AttachmentIDs AttachmentIDList `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type MessageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type MessagesPageResponse struct {
|
||||
Items []MessageResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package dto
|
||||
|
||||
import "time"
|
||||
|
||||
const timestampLayout = "2006-01-02T15:04:05.000000Z"
|
||||
|
||||
// Timestamp сериализуется в UTC всегда с 6 цифрами дробной части. Стандартный формат
|
||||
// time.Time отбрасывает нули в конце (…17.95188Z): это корректный RFC 3339, но такое значение
|
||||
// не разбирает datetime.fromisoformat в Python 3.9–3.10, на которых идут публичные тесты.
|
||||
type Timestamp struct {
|
||||
time.Time
|
||||
}
|
||||
|
||||
func NewTimestamp(t time.Time) Timestamp {
|
||||
return Timestamp{Time: t}
|
||||
}
|
||||
|
||||
func (t Timestamp) MarshalJSON() ([]byte, error) {
|
||||
return []byte(`"` + t.UTC().Format(timestampLayout) + `"`), nil
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package dto
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type UserResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
|
||||
type SessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt Timestamp `json:"expires_at"`
|
||||
User UserResponse `json:"user"`
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const (
|
||||
CodeInvalidRequest = "invalid_request"
|
||||
CodeUnauthorized = "unauthorized"
|
||||
CodeNotFound = "not_found"
|
||||
CodeConflict = "conflict"
|
||||
CodePayloadTooLarge = "payload_too_large"
|
||||
CodeUnsupportedMedia = "unsupported_media_type"
|
||||
CodeRateLimited = "rate_limited"
|
||||
CodeUnavailable = "unavailable"
|
||||
CodeInternalError = "internal_error"
|
||||
)
|
||||
|
||||
type errorBody struct {
|
||||
Error errorPayload `json:"error"`
|
||||
}
|
||||
|
||||
type errorPayload struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
var (
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrUnsupportedMedia = errors.New("unsupported media type")
|
||||
)
|
||||
|
||||
func Classify(err error) (status int, code, message string) {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrIdempotencyConflict):
|
||||
return http.StatusConflict, CodeConflict, "Idempotency-Key was already used with a different request"
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return http.StatusNotFound, CodeNotFound, "Object not found"
|
||||
case errors.Is(err, domain.ErrConflict):
|
||||
return http.StatusConflict, CodeConflict, "Resource already exists"
|
||||
case errors.Is(err, domain.ErrInvalidArgument):
|
||||
return http.StatusBadRequest, CodeInvalidRequest, "Invalid request arguments"
|
||||
case errors.Is(err, domain.ErrUnavailable):
|
||||
return http.StatusServiceUnavailable, CodeUnavailable, "Service temporarily unavailable"
|
||||
case errors.Is(err, domain.ErrPayloadTooLarge):
|
||||
return http.StatusRequestEntityTooLarge, CodePayloadTooLarge, "Request body too large"
|
||||
case errors.Is(err, domain.ErrRateLimited):
|
||||
return http.StatusTooManyRequests, CodeRateLimited, "Too many concurrent requests"
|
||||
case errors.Is(err, ErrUnauthorized), errors.Is(err, domain.ErrUnauthorized):
|
||||
return http.StatusUnauthorized, CodeUnauthorized, "Identification required"
|
||||
case errors.Is(err, domain.ErrUnsupportedMedia):
|
||||
return http.StatusUnsupportedMediaType, CodeUnsupportedMedia, "Expected a valid PNG or JPEG image"
|
||||
case errors.Is(err, ErrUnsupportedMedia):
|
||||
return http.StatusUnsupportedMediaType, CodeUnsupportedMedia, "Expected Content-Type: application/json"
|
||||
}
|
||||
|
||||
var vErr *validate.Error
|
||||
if errors.As(err, &vErr) {
|
||||
return http.StatusBadRequest, CodeInvalidRequest, vErr.Error()
|
||||
}
|
||||
|
||||
return http.StatusInternalServerError, CodeInternalError, "Internal server error"
|
||||
}
|
||||
|
||||
func WriteError(c echo.Context, err error) error {
|
||||
status, code, msg := Classify(err)
|
||||
if status == http.StatusTooManyRequests {
|
||||
c.Response().Header().Set("Retry-After", "1")
|
||||
}
|
||||
return c.JSON(status, errorBody{
|
||||
Error: errorPayload{
|
||||
Code: code,
|
||||
Message: msg,
|
||||
RequestID: c.Response().Header().Get(echo.HeaderXRequestID),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func healthLive(c echo.Context) error {
|
||||
return c.JSON(http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
func healthReady(isReady func() bool) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if !isReady() {
|
||||
return echo.NewHTTPError(http.StatusServiceUnavailable, "Service unavailable")
|
||||
}
|
||||
return c.JSON(http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
const headerIdempotencyKey = "Idempotency-Key"
|
||||
|
||||
type messagesHandler struct {
|
||||
messages service.MessagesService
|
||||
}
|
||||
|
||||
func (h *messagesHandler) send(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
chatID := c.Param("chat_id")
|
||||
|
||||
var req dto.CreateMessageRequest
|
||||
if err := decodeJSON(c.Request().Body, &req); err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
if req.Text == nil {
|
||||
return WriteError(c, &validate.Error{Field: "text", Reason: "is required"})
|
||||
}
|
||||
|
||||
msg, err := h.messages.Send(c.Request().Context(), callerID, chatID, c.Request().Header.Get(headerIdempotencyKey), *req.Text, req.AttachmentIDs)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, toMessageResponse(msg))
|
||||
}
|
||||
|
||||
func (h *messagesHandler) list(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
chatID := c.Param("chat_id")
|
||||
|
||||
limit, cursor, err := parsePageParams(c)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
page, err := h.messages.List(c.Request().Context(), callerID, chatID, cursor, limit)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, toMessagesPage(page))
|
||||
}
|
||||
|
||||
func toMessageResponse(m domain.Message) dto.MessageResponse {
|
||||
return dto.MessageResponse{
|
||||
ID: m.ID,
|
||||
ChatID: m.ChatID,
|
||||
SenderID: m.AuthorID,
|
||||
Text: m.Text,
|
||||
CreatedAt: dto.NewTimestamp(m.CreatedAt),
|
||||
// Без вложений в JSON должен быть [], а не null.
|
||||
AttachmentIDs: append([]string{}, m.AttachmentIDs...),
|
||||
}
|
||||
}
|
||||
|
||||
func toMessagesPage(p domain.Page[domain.Message]) dto.MessagesPageResponse {
|
||||
items := make([]dto.MessageResponse, 0, len(p.Items))
|
||||
for _, m := range p.Items {
|
||||
items = append(items, toMessageResponse(m))
|
||||
}
|
||||
var next *string
|
||||
if p.NextCursor != "" {
|
||||
s := p.NextCursor
|
||||
next = &s
|
||||
}
|
||||
return dto.MessagesPageResponse{Items: items, NextCursor: next}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const AuthTokenKey = "auth_token"
|
||||
|
||||
const (
|
||||
BearerChallenge = `Bearer realm="messenger"`
|
||||
BasicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
)
|
||||
|
||||
type Authenticator interface {
|
||||
Authenticate(ctx context.Context, token string) (userID string, err error)
|
||||
}
|
||||
|
||||
func Bearer(auth Authenticator) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
tok, ok := BearerToken(c.Request().Header.Get(echo.HeaderAuthorization))
|
||||
if !ok {
|
||||
return unauthorized(c, BearerChallenge, "Bearer token required")
|
||||
}
|
||||
userID, err := auth.Authenticate(c.Request().Context(), tok)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrUnauthorized) {
|
||||
return unauthorized(c, BearerChallenge, "Invalid or expired session")
|
||||
}
|
||||
return err
|
||||
}
|
||||
c.Set(AuthUserIDKey, userID)
|
||||
c.Set(AuthTokenKey, tok)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BearerToken(header string) (string, bool) {
|
||||
scheme, tok, found := strings.Cut(header, " ")
|
||||
if !found || !strings.EqualFold(scheme, "Bearer") {
|
||||
return "", false
|
||||
}
|
||||
tok = strings.TrimSpace(tok)
|
||||
return tok, tok != ""
|
||||
}
|
||||
|
||||
func unauthorized(c echo.Context, challenge, msg string) error {
|
||||
c.Response().Header().Set(echo.HeaderWWWAuthenticate, challenge)
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, msg)
|
||||
}
|
||||
|
||||
func Unauthorized(c echo.Context, challenge, msg string) error {
|
||||
return unauthorized(c, challenge, msg)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
func ContentType() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if !methodHasBody(c.Request().Method) {
|
||||
return next(c)
|
||||
}
|
||||
if !isApplicationJSON(c.Request().Header.Get(echo.HeaderContentType)) {
|
||||
return echo.NewHTTPError(http.StatusUnsupportedMediaType, "Expected Content-Type: application/json")
|
||||
}
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func methodHasBody(method string) bool {
|
||||
switch method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isApplicationJSON(ct string) bool {
|
||||
if ct == "" {
|
||||
return false
|
||||
}
|
||||
mediatype, _, err := mime.ParseMediaType(ct)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(mediatype, "application/json")
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package middleware
|
||||
|
||||
import "github.com/labstack/echo/v4"
|
||||
|
||||
const HeaderInstanceID = "X-Instance-Id"
|
||||
|
||||
func InstanceID(id string) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
c.Response().Header().Set(HeaderInstanceID, id)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"io"
|
||||
"runtime"
|
||||
"slices"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
// BodyLimit ограничивает тело запроса. Маршруты из exemptRoutes применяют собственный лимит.
|
||||
func BodyLimit(maxBytes int64, exemptRoutes ...string) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if !methodHasBody(c.Request().Method) || slices.Contains(exemptRoutes, c.Path()) {
|
||||
return next(c)
|
||||
}
|
||||
if cl := c.Request().ContentLength; cl > maxBytes {
|
||||
return domain.ErrPayloadTooLarge
|
||||
}
|
||||
c.Request().Body = &limitedBody{
|
||||
raw: c.Request().Body,
|
||||
maxLeft: maxBytes,
|
||||
}
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type limitedBody struct {
|
||||
raw io.ReadCloser
|
||||
maxLeft int64
|
||||
}
|
||||
|
||||
func (b *limitedBody) Read(p []byte) (int, error) {
|
||||
if int64(len(p)) > b.maxLeft+1 {
|
||||
p = p[:b.maxLeft+1]
|
||||
}
|
||||
n, err := b.raw.Read(p)
|
||||
b.maxLeft -= int64(n)
|
||||
if b.maxLeft < 0 {
|
||||
return n, domain.ErrPayloadTooLarge
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (b *limitedBody) Close() error {
|
||||
return b.raw.Close()
|
||||
}
|
||||
|
||||
func InFlight(maxInFlight int) echo.MiddlewareFunc {
|
||||
sem := make(chan struct{}, maxInFlight)
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if isHealthPath(c.Request().URL.Path) {
|
||||
return next(c)
|
||||
}
|
||||
select {
|
||||
case sem <- struct{}{}:
|
||||
defer func() { <-sem }()
|
||||
return next(c)
|
||||
default:
|
||||
return domain.ErrRateLimited
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func MemoryGuard(maxHeapBytes uint64, poll time.Duration) echo.MiddlewareFunc {
|
||||
var sample atomic.Uint64
|
||||
|
||||
readOnce := func() {
|
||||
var m runtime.MemStats
|
||||
runtime.ReadMemStats(&m)
|
||||
if m.HeapInuse > maxHeapBytes {
|
||||
runtime.GC()
|
||||
runtime.ReadMemStats(&m)
|
||||
}
|
||||
sample.Store(m.HeapInuse)
|
||||
}
|
||||
readOnce()
|
||||
|
||||
if poll > 0 {
|
||||
go func() {
|
||||
t := time.NewTicker(poll)
|
||||
defer t.Stop()
|
||||
for range t.C {
|
||||
readOnce()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if !methodHasBody(c.Request().Method) || isHealthPath(c.Request().URL.Path) {
|
||||
return next(c)
|
||||
}
|
||||
if sample.Load() > maxHeapBytes {
|
||||
return domain.ErrUnavailable
|
||||
}
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isHealthPath(path string) bool {
|
||||
return path == "/health/live" || path == "/health/ready"
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const AuthUserIDKey = "caller_id"
|
||||
|
||||
func Logger(logger *slog.Logger) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
start := time.Now()
|
||||
if err := next(c); err != nil {
|
||||
c.Error(err)
|
||||
}
|
||||
status := c.Response().Status
|
||||
|
||||
rid, _ := c.Get(RequestIDKey).(string)
|
||||
uid, _ := c.Get(AuthUserIDKey).(string)
|
||||
|
||||
attrs := []slog.Attr{
|
||||
slog.String("request_id", rid),
|
||||
slog.String("method", c.Request().Method),
|
||||
slog.String("path", c.Request().URL.Path),
|
||||
slog.Int("status", status),
|
||||
slog.Int64("duration_ms", time.Since(start).Milliseconds()),
|
||||
slog.String("remote_ip", c.RealIP()),
|
||||
}
|
||||
if uid != "" {
|
||||
attrs = append(attrs, slog.String("user_id", uid))
|
||||
}
|
||||
|
||||
level := slog.LevelInfo
|
||||
switch {
|
||||
case status >= 500:
|
||||
level = slog.LevelError
|
||||
case status >= 400:
|
||||
level = slog.LevelWarn
|
||||
}
|
||||
logger.LogAttrs(c.Request().Context(), level, "http request", attrs...)
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
func Recover(logger *slog.Logger) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) (err error) {
|
||||
defer func() {
|
||||
r := recover()
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
rid, _ := c.Get(RequestIDKey).(string)
|
||||
logger.Error("panic recovered",
|
||||
slog.String("request_id", rid),
|
||||
slog.String("method", c.Request().Method),
|
||||
slog.String("path", c.Request().URL.Path),
|
||||
slog.Any("panic", r),
|
||||
slog.String("stack", string(debug.Stack())),
|
||||
)
|
||||
err = echo.NewHTTPError(http.StatusInternalServerError, "Internal server error")
|
||||
}()
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const RequestIDKey = "request_id"
|
||||
|
||||
func RequestID() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
rid := c.Request().Header.Get(echo.HeaderXRequestID)
|
||||
if rid == "" {
|
||||
rid = uuid.NewString()
|
||||
}
|
||||
c.Response().Header().Set(echo.HeaderXRequestID, rid)
|
||||
c.Set(RequestIDKey, rid)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
)
|
||||
|
||||
func registerRoutes(e *echo.Echo, d Deps, isReady func() bool) {
|
||||
e.GET("/health/live", healthLive)
|
||||
e.GET("/health/ready", healthReady(isReady))
|
||||
|
||||
usersH := &usersHandler{users: d.Users}
|
||||
chatsH := &chatsHandler{chats: d.Chats}
|
||||
messagesH := &messagesHandler{messages: d.Messages}
|
||||
authH := &authHandler{auth: d.Auth}
|
||||
attachmentsH := &attachmentsHandler{attachments: d.Attachments}
|
||||
|
||||
auth := middleware.Bearer(d.Auth)
|
||||
|
||||
jsonBody := middleware.ContentType()
|
||||
|
||||
v1 := e.Group("/api/v1")
|
||||
v1.POST("/users", usersH.create, jsonBody)
|
||||
v1.POST("/auth/sessions", authH.createSession)
|
||||
v1.DELETE("/auth/sessions/current", authH.revokeSession, auth)
|
||||
v1.GET("/users/me", usersH.me, auth)
|
||||
v1.POST("/chats", chatsH.create, auth, jsonBody)
|
||||
v1.GET("/chats", chatsH.list, auth)
|
||||
v1.GET("/chats/:chat_id", chatsH.get, auth)
|
||||
v1.POST("/chats/:chat_id/messages", messagesH.send, auth, jsonBody)
|
||||
v1.GET("/chats/:chat_id/messages", messagesH.list, auth)
|
||||
// Тело здесь не JSON: Content-Type и размер проверяет сервис, после проверки доступа.
|
||||
v1.POST("/chats/:chat_id/attachments", attachmentsH.upload, uploadTransfer, auth)
|
||||
v1.GET("/attachments/:attachment_id", attachmentsH.get, auth)
|
||||
v1.GET("/attachments/:attachment_id/content", attachmentsH.content, auth)
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
nethttp "net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
)
|
||||
|
||||
type Deps struct {
|
||||
Config *config.Config
|
||||
Logger *slog.Logger
|
||||
Store store.Store
|
||||
Auth service.AuthService
|
||||
Users service.UsersService
|
||||
Chats service.ChatsService
|
||||
Messages service.MessagesService
|
||||
Attachments service.AttachmentsService
|
||||
|
||||
Ready func(ctx context.Context) error
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
e *echo.Echo
|
||||
cfg config.HTTP
|
||||
logger *slog.Logger
|
||||
shutting atomic.Bool
|
||||
ready func(ctx context.Context) error
|
||||
}
|
||||
|
||||
func NewServer(d Deps) *Server {
|
||||
s := &Server{
|
||||
e: echo.New(),
|
||||
cfg: d.Config.HTTP,
|
||||
logger: d.Logger,
|
||||
ready: d.Ready,
|
||||
}
|
||||
|
||||
s.e.HideBanner = true
|
||||
s.e.HidePort = true
|
||||
s.e.HTTPErrorHandler = s.httpErrorHandler
|
||||
|
||||
s.e.Server.ReadTimeout = time.Duration(s.cfg.ReadTimeoutMs) * time.Millisecond
|
||||
s.e.Server.WriteTimeout = time.Duration(s.cfg.WriteTimeoutMs) * time.Millisecond
|
||||
s.e.Server.IdleTimeout = time.Duration(s.cfg.IdleTimeoutMs) * time.Millisecond
|
||||
|
||||
s.e.Use(middleware.InstanceID(d.Config.InstanceID))
|
||||
s.e.Use(middleware.Recover(d.Logger))
|
||||
s.e.Use(middleware.RequestID())
|
||||
s.e.Use(middleware.Logger(d.Logger))
|
||||
s.e.Use(middleware.InFlight(d.Config.Limits.MaxInFlight))
|
||||
s.e.Use(middleware.BodyLimit(d.Config.Limits.MaxBodyBytes, routeUploadAttachment))
|
||||
s.e.Use(middleware.MemoryGuard(d.Config.Limits.MaxHeapBytes, 100*time.Millisecond))
|
||||
|
||||
registerRoutes(s.e, d, s.IsReady)
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) Start() error {
|
||||
s.logger.Info("http server starting", slog.String("addr", s.cfg.Addr))
|
||||
err := s.e.Start(s.cfg.Addr)
|
||||
if errors.Is(err, nethttp.ErrServerClosed) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Drain переводит readiness в 503 и ждёт d, продолжая обслуживать запросы: за это время
|
||||
// балансировщик выводит реплику, и новые запросы не попадают на закрытый listener.
|
||||
func (s *Server) Drain(d time.Duration) {
|
||||
s.shutting.Store(true)
|
||||
s.logger.Info("http server draining", slog.Duration("for", d))
|
||||
time.Sleep(d)
|
||||
}
|
||||
|
||||
func (s *Server) Shutdown(ctx context.Context) error {
|
||||
s.shutting.Store(true)
|
||||
s.logger.Info("http server shutting down")
|
||||
return s.e.Shutdown(ctx)
|
||||
}
|
||||
|
||||
func (s *Server) IsReady() bool {
|
||||
if s.shutting.Load() {
|
||||
return false
|
||||
}
|
||||
if s.ready == nil {
|
||||
return true
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), readyTimeout)
|
||||
defer cancel()
|
||||
return s.ready(ctx) == nil
|
||||
}
|
||||
|
||||
const readyTimeout = time.Second
|
||||
|
||||
func (s *Server) Handler() nethttp.Handler {
|
||||
return s.e
|
||||
}
|
||||
|
||||
func (s *Server) httpErrorHandler(err error, c echo.Context) {
|
||||
if c.Response().Committed {
|
||||
return
|
||||
}
|
||||
|
||||
var httpErr *echo.HTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
code := codeFromStatus(httpErr.Code)
|
||||
msg, _ := httpErr.Message.(string)
|
||||
if msg == "" || msg == nethttp.StatusText(httpErr.Code) {
|
||||
msg = messageFor(httpErr.Code, code)
|
||||
}
|
||||
_ = c.JSON(httpErr.Code, errorBody{
|
||||
Error: errorPayload{
|
||||
Code: code,
|
||||
Message: msg,
|
||||
RequestID: c.Response().Header().Get(echo.HeaderXRequestID),
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
_ = WriteError(c, err)
|
||||
}
|
||||
|
||||
var codesByStatus = map[int]string{
|
||||
nethttp.StatusBadRequest: CodeInvalidRequest,
|
||||
nethttp.StatusUnauthorized: CodeUnauthorized,
|
||||
nethttp.StatusNotFound: CodeNotFound,
|
||||
nethttp.StatusMethodNotAllowed: CodeInvalidRequest,
|
||||
nethttp.StatusConflict: CodeConflict,
|
||||
nethttp.StatusRequestEntityTooLarge: CodePayloadTooLarge,
|
||||
nethttp.StatusUnsupportedMediaType: CodeUnsupportedMedia,
|
||||
nethttp.StatusTooManyRequests: CodeRateLimited,
|
||||
nethttp.StatusServiceUnavailable: CodeUnavailable,
|
||||
}
|
||||
|
||||
func codeFromStatus(status int) string {
|
||||
if c, ok := codesByStatus[status]; ok {
|
||||
return c
|
||||
}
|
||||
return CodeInternalError
|
||||
}
|
||||
|
||||
var messagesByStatus = map[int]string{
|
||||
nethttp.StatusMethodNotAllowed: "Method not allowed",
|
||||
}
|
||||
|
||||
func messageFor(status int, code string) string {
|
||||
if m, ok := messagesByStatus[status]; ok {
|
||||
return m
|
||||
}
|
||||
return defaultMessages[code]
|
||||
}
|
||||
|
||||
var defaultMessages = map[string]string{
|
||||
CodeInvalidRequest: "Invalid request",
|
||||
CodeUnauthorized: "Identification required",
|
||||
CodeNotFound: "Object not found",
|
||||
CodeConflict: "Conflict",
|
||||
CodePayloadTooLarge: "Request body too large",
|
||||
CodeUnsupportedMedia: "Unsupported Content-Type",
|
||||
CodeRateLimited: "Too many requests",
|
||||
CodeUnavailable: "Service unavailable",
|
||||
CodeInternalError: "Internal server error",
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
type usersHandler struct {
|
||||
users service.UsersService
|
||||
}
|
||||
|
||||
func (h *usersHandler) create(c echo.Context) error {
|
||||
var req dto.CreateUserRequest
|
||||
if err := decodeJSON(c.Request().Body, &req); err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
user, err := h.users.Register(c.Request().Context(), req.Username, req.DisplayName, req.Password)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, toUserResponse(user))
|
||||
}
|
||||
|
||||
func (h *usersHandler) me(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
user, err := h.users.Me(c.Request().Context(), callerID)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, toUserResponse(user))
|
||||
}
|
||||
|
||||
func toUserResponse(u domain.User) dto.UserResponse {
|
||||
return dto.UserResponse{
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
DisplayName: u.DisplayName,
|
||||
CreatedAt: dto.NewTimestamp(u.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func decodeJSON(body io.Reader, dst any) error {
|
||||
data, err := io.ReadAll(body)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrPayloadTooLarge) {
|
||||
return err
|
||||
}
|
||||
return &validate.Error{Field: "body", Reason: "cannot read body"}
|
||||
}
|
||||
if !utf8.Valid(data) {
|
||||
return &validate.Error{Field: "body", Reason: "invalid UTF-8"}
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return &validate.Error{Field: "body", Reason: jsonErrorReason(err)}
|
||||
}
|
||||
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
|
||||
return &validate.Error{Field: "body", Reason: "unexpected data after JSON object"}
|
||||
}
|
||||
return checkExactKeys(data, dst)
|
||||
}
|
||||
|
||||
func checkExactKeys(data []byte, dst any) error {
|
||||
var obj map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &obj); err != nil {
|
||||
return nil
|
||||
}
|
||||
allowed := make(map[string]struct{})
|
||||
t := reflect.TypeOf(dst).Elem()
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
|
||||
allowed[name] = struct{}{}
|
||||
}
|
||||
for key := range obj {
|
||||
if _, ok := allowed[key]; !ok {
|
||||
return &validate.Error{Field: "body", Reason: fmt.Sprintf("unknown field %q", key)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func jsonErrorReason(err error) string {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return "empty body"
|
||||
}
|
||||
var typeErr *json.UnmarshalTypeError
|
||||
if errors.As(err, &typeErr) {
|
||||
if typeErr.Field == "" {
|
||||
return "expected a JSON object"
|
||||
}
|
||||
return fmt.Sprintf("field %q: invalid type", typeErr.Field)
|
||||
}
|
||||
if name, ok := strings.CutPrefix(err.Error(), "json: unknown field "); ok {
|
||||
return "unknown field " + name
|
||||
}
|
||||
return "invalid JSON"
|
||||
}
|
||||
Vendored
+478
@@ -0,0 +1,478 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
ModeOff = "off"
|
||||
ModeNaive = "naive"
|
||||
ModeSafe = "safe"
|
||||
)
|
||||
|
||||
type Source interface {
|
||||
store.MessageStore
|
||||
IsMember(ctx context.Context, chatID, userID string) (bool, error)
|
||||
HistoryPage(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error)
|
||||
}
|
||||
|
||||
// Outbox хранит долг инвалидации в источнике истины, чтобы он пережил
|
||||
// рестарт API. Без него отложенная инвалидация живёт только в памяти.
|
||||
type Outbox interface {
|
||||
AddPendingInvalidation(ctx context.Context, chatID string) (int64, error)
|
||||
PendingInvalidations(ctx context.Context) (map[string]int64, error)
|
||||
ResolvePendingInvalidation(ctx context.Context, chatID string, gen int64) error
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
Mode string
|
||||
Outbox Outbox
|
||||
PageTTL time.Duration
|
||||
LockTTL time.Duration
|
||||
FillDelay time.Duration
|
||||
Logger *slog.Logger
|
||||
}
|
||||
|
||||
var _ store.MessageStore = (*Messages)(nil)
|
||||
|
||||
// pendingEntry — несброшенная версия чата. seq меняется при каждом новом
|
||||
// сбое: повтор снимает запись, только если seq не изменился с его снимка.
|
||||
// gen — поколение строки в Outbox (0 — не записана).
|
||||
type pendingEntry struct {
|
||||
seq uint64
|
||||
gen int64
|
||||
}
|
||||
|
||||
type Messages struct {
|
||||
src Source
|
||||
rdb *redis.Client
|
||||
opt Options
|
||||
group singleflight.Group
|
||||
log *slog.Logger
|
||||
|
||||
downUntil atomic.Int64
|
||||
// loaded: долг инвалидации из Outbox прочитан. До этого любой чат может
|
||||
// иметь устаревшую версию, поэтому все чтения идут мимо кэша.
|
||||
loaded atomic.Bool
|
||||
|
||||
mu sync.Mutex
|
||||
pending map[string]pendingEntry
|
||||
seq uint64
|
||||
stop chan struct{}
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
const (
|
||||
memberTTL = 24 * time.Hour
|
||||
versionTTL = 24 * time.Hour
|
||||
breakerPause = time.Second
|
||||
retryInterval = 200 * time.Millisecond
|
||||
pollInterval = 5 * time.Millisecond
|
||||
defaultPageTTL = 30 * time.Second
|
||||
defaultLockTTL = 500 * time.Millisecond
|
||||
)
|
||||
|
||||
func New(src Source, rdb *redis.Client, opt Options) *Messages {
|
||||
if opt.PageTTL <= 0 {
|
||||
opt.PageTTL = defaultPageTTL
|
||||
}
|
||||
if opt.LockTTL <= 0 {
|
||||
opt.LockTTL = defaultLockTTL
|
||||
}
|
||||
if opt.Logger == nil {
|
||||
opt.Logger = slog.Default()
|
||||
}
|
||||
m := &Messages{
|
||||
src: src,
|
||||
rdb: rdb,
|
||||
opt: opt,
|
||||
log: opt.Logger,
|
||||
pending: make(map[string]pendingEntry),
|
||||
stop: make(chan struct{}),
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
m.loaded.Store(opt.Outbox == nil || opt.Mode != ModeSafe)
|
||||
go m.retryLoop()
|
||||
return m
|
||||
}
|
||||
|
||||
func Connect(cfg config.HistoryCache) (*redis.Client, error) {
|
||||
url := cfg.URL
|
||||
if cfg.URLFile != "" {
|
||||
b, err := os.ReadFile(cfg.URLFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cache: read HISTORY_CACHE_URL_FILE: %w", err)
|
||||
}
|
||||
url = strings.TrimSpace(string(b))
|
||||
}
|
||||
if url == "" {
|
||||
return nil, errors.New("cache: HISTORY_CACHE_URL_FILE or HISTORY_CACHE_URL is required unless HISTORY_CACHE=off")
|
||||
}
|
||||
opts, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, errors.New("cache: invalid HISTORY_CACHE_URL")
|
||||
}
|
||||
timeout := time.Duration(cfg.TimeoutMs) * time.Millisecond
|
||||
opts.PoolSize = cfg.PoolSize
|
||||
opts.DialTimeout = timeout
|
||||
opts.ReadTimeout = timeout
|
||||
opts.WriteTimeout = timeout
|
||||
opts.PoolTimeout = timeout
|
||||
opts.MaxRetries = -1 // без повторов: промах кэша дешевле ожидания
|
||||
return redis.NewClient(opts), nil
|
||||
}
|
||||
|
||||
func (m *Messages) Close() {
|
||||
close(m.stop)
|
||||
<-m.done
|
||||
}
|
||||
|
||||
func (m *Messages) AddMessage(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) {
|
||||
msg, err := m.src.AddMessage(ctx, callerID, chatID, idempotencyKey, text, attachmentIDs)
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
// Инвалидация нужна и при повторе: реплика, выполнившая COMMIT, могла упасть до
|
||||
// сброса кэша, и тогда ответ 201 на повтор — первое подтверждение этого сообщения.
|
||||
ictx := context.WithoutCancel(ctx)
|
||||
switch m.opt.Mode {
|
||||
case ModeNaive:
|
||||
m.naiveInvalidate(ictx, chatID)
|
||||
case ModeSafe:
|
||||
if err := m.rdb.Del(ictx, verKey(chatID)).Err(); err != nil {
|
||||
m.markDown(err)
|
||||
m.addPending(ictx, chatID)
|
||||
}
|
||||
}
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func (m *Messages) ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
if m.opt.Mode == ModeOff || m.bypass(chatID) {
|
||||
return m.src.ListMessages(ctx, callerID, chatID, cursor, limit)
|
||||
}
|
||||
if err := m.checkMember(ctx, chatID, callerID); err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
if m.opt.Mode == ModeNaive {
|
||||
return m.naiveList(ctx, chatID, cursor, limit)
|
||||
}
|
||||
return m.safeList(ctx, chatID, cursor, limit)
|
||||
}
|
||||
|
||||
func (m *Messages) checkMember(ctx context.Context, chatID, userID string) error {
|
||||
key := "hc:member:" + chatID + ":" + userID
|
||||
if !m.isDown() {
|
||||
v, err := m.rdb.Get(ctx, key).Result()
|
||||
if err == nil && v == "1" {
|
||||
return nil
|
||||
}
|
||||
m.markDown(err)
|
||||
}
|
||||
ok, err := m.src.IsMember(ctx, chatID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
// Отрицательный ответ не кэшируем.
|
||||
return domain.ErrNotFound
|
||||
}
|
||||
if !m.isDown() {
|
||||
m.markDown(m.rdb.Set(ctx, key, "1", memberTTL).Err())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Messages) naiveList(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
key := pageKey("hc:naive:"+chatID, cursor, limit)
|
||||
if page, ok := m.getPage(ctx, key); ok {
|
||||
return page, nil
|
||||
}
|
||||
page, err := m.src.HistoryPage(ctx, chatID, cursor, limit)
|
||||
if err != nil {
|
||||
return page, err
|
||||
}
|
||||
m.sleepFill(ctx)
|
||||
if b, err := encodePage(page); err == nil {
|
||||
setKey := "hc:naive:keys:" + chatID
|
||||
_, err := m.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
||||
p.Set(ctx, key, b, m.opt.PageTTL)
|
||||
p.SAdd(ctx, setKey, key)
|
||||
p.Expire(ctx, setKey, m.opt.PageTTL)
|
||||
return nil
|
||||
})
|
||||
m.markDown(err)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (m *Messages) naiveInvalidate(ctx context.Context, chatID string) {
|
||||
setKey := "hc:naive:keys:" + chatID
|
||||
keys, err := m.rdb.SMembers(ctx, setKey).Result()
|
||||
if err != nil {
|
||||
m.markDown(err)
|
||||
return
|
||||
}
|
||||
m.markDown(m.rdb.Del(ctx, append(keys, setKey)...).Err())
|
||||
}
|
||||
|
||||
func (m *Messages) safeList(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
ver, err := m.version(ctx, chatID)
|
||||
if err != nil {
|
||||
m.markDown(err)
|
||||
return m.src.HistoryPage(ctx, chatID, cursor, limit)
|
||||
}
|
||||
key := pageKey("hc:page:"+chatID+":"+ver, cursor, limit)
|
||||
if page, ok := m.getPage(ctx, key); ok {
|
||||
return page, nil
|
||||
}
|
||||
v, err, _ := m.group.Do(key, func() (any, error) {
|
||||
return m.fill(context.WithoutCancel(ctx), key, chatID, cursor, limit)
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
return v.(domain.Page[domain.Message]), nil
|
||||
}
|
||||
|
||||
func (m *Messages) version(ctx context.Context, chatID string) (string, error) {
|
||||
key := verKey(chatID)
|
||||
v, err := m.rdb.Get(ctx, key).Result()
|
||||
if err == nil {
|
||||
return v, nil
|
||||
}
|
||||
if !errors.Is(err, redis.Nil) {
|
||||
return "", err
|
||||
}
|
||||
fresh := randomVersion()
|
||||
old, err := m.rdb.SetArgs(ctx, key, fresh, redis.SetArgs{Mode: "NX", Get: true, TTL: versionTTL}).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return fresh, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return old, nil
|
||||
}
|
||||
|
||||
var unlockScript = redis.NewScript(`
|
||||
if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) end
|
||||
return 0`)
|
||||
|
||||
func (m *Messages) fill(ctx context.Context, key, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
lockKey := "hc:lock:" + key
|
||||
token := randomVersion()
|
||||
locked, err := m.rdb.SetNX(ctx, lockKey, token, m.opt.LockTTL).Result()
|
||||
if err != nil {
|
||||
m.markDown(err)
|
||||
return m.src.HistoryPage(ctx, chatID, cursor, limit)
|
||||
}
|
||||
if !locked {
|
||||
deadline := time.Now().Add(m.opt.LockTTL)
|
||||
for time.Now().Before(deadline) {
|
||||
time.Sleep(pollInterval)
|
||||
if page, ok := m.getPage(ctx, key); ok {
|
||||
return page, nil
|
||||
}
|
||||
}
|
||||
return m.src.HistoryPage(ctx, chatID, cursor, limit)
|
||||
}
|
||||
defer unlockScript.Run(ctx, m.rdb, []string{lockKey}, token)
|
||||
|
||||
page, err := m.src.HistoryPage(ctx, chatID, cursor, limit)
|
||||
if err != nil {
|
||||
return page, err
|
||||
}
|
||||
m.sleepFill(ctx)
|
||||
if b, err := encodePage(page); err == nil {
|
||||
m.markDown(m.rdb.Set(ctx, key, b, m.opt.PageTTL).Err())
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// addPending вызывается до ответа 201: после него чат читается мимо кэша,
|
||||
// пока версия не будет сброшена, в том числе после рестарта API.
|
||||
func (m *Messages) addPending(ctx context.Context, chatID string) {
|
||||
m.markPending(chatID, 0)
|
||||
if m.opt.Outbox == nil {
|
||||
m.log.Warn("history cache invalidation deferred", slog.String("chat_id", chatID))
|
||||
return
|
||||
}
|
||||
gen, err := m.opt.Outbox.AddPendingInvalidation(ctx, chatID)
|
||||
if err != nil {
|
||||
m.log.Error("history cache invalidation deferred in memory only, lost on restart",
|
||||
slog.String("chat_id", chatID), slog.Any("err", err))
|
||||
return
|
||||
}
|
||||
m.markPending(chatID, gen)
|
||||
m.log.Warn("history cache invalidation deferred",
|
||||
slog.String("chat_id", chatID), slog.Int64("gen", gen))
|
||||
}
|
||||
|
||||
// markPending всегда выдаёт новый seq, чтобы повтор, начатый раньше, не снял
|
||||
// запись. gen не уменьшается.
|
||||
func (m *Messages) markPending(chatID string, gen int64) {
|
||||
m.mu.Lock()
|
||||
m.seq++
|
||||
e := m.pending[chatID]
|
||||
e.seq = m.seq
|
||||
e.gen = max(e.gen, gen)
|
||||
m.pending[chatID] = e
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
func (m *Messages) bypass(chatID string) bool {
|
||||
if m.isDown() || !m.loaded.Load() {
|
||||
return true
|
||||
}
|
||||
m.mu.Lock()
|
||||
_, ok := m.pending[chatID]
|
||||
m.mu.Unlock()
|
||||
return ok
|
||||
}
|
||||
|
||||
func (m *Messages) loadPending() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
rows, err := m.opt.Outbox.PendingInvalidations(ctx)
|
||||
if err != nil {
|
||||
m.log.Warn("history cache: pending invalidations not loaded, bypassing", slog.Any("err", err))
|
||||
return
|
||||
}
|
||||
for id, gen := range rows {
|
||||
m.markPending(id, gen)
|
||||
}
|
||||
m.loaded.Store(true)
|
||||
if len(rows) > 0 {
|
||||
m.log.Info("history cache: pending invalidations loaded", slog.Int("chats", len(rows)))
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Messages) retryLoop() {
|
||||
defer close(m.done)
|
||||
t := time.NewTicker(retryInterval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
if !m.loaded.Load() {
|
||||
m.loadPending()
|
||||
}
|
||||
m.retryPending()
|
||||
select {
|
||||
case <-m.stop:
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Messages) retryPending() {
|
||||
m.mu.Lock()
|
||||
chats := make(map[string]pendingEntry, len(m.pending))
|
||||
for id, e := range m.pending {
|
||||
chats[id] = e
|
||||
}
|
||||
m.mu.Unlock()
|
||||
for id, e := range chats {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
err := m.rdb.Del(ctx, verKey(id)).Err()
|
||||
if err == nil && e.gen > 0 {
|
||||
err = m.opt.Outbox.ResolvePendingInvalidation(ctx, id, e.gen)
|
||||
}
|
||||
cancel()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
m.resolved(id, e)
|
||||
}
|
||||
}
|
||||
|
||||
// resolved снимает запись, если после снимка e не было нового сбоя.
|
||||
func (m *Messages) resolved(chatID string, e pendingEntry) {
|
||||
m.mu.Lock()
|
||||
if m.pending[chatID].seq == e.seq {
|
||||
delete(m.pending, chatID)
|
||||
}
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
func (m *Messages) isDown() bool {
|
||||
return time.Now().UnixNano() < m.downUntil.Load()
|
||||
}
|
||||
|
||||
func (m *Messages) markDown(err error) {
|
||||
if err == nil || errors.Is(err, redis.Nil) {
|
||||
return
|
||||
}
|
||||
if !m.isDown() {
|
||||
m.log.Warn("history cache unavailable, bypassing", slog.Any("err", err))
|
||||
}
|
||||
m.downUntil.Store(time.Now().Add(breakerPause).UnixNano())
|
||||
}
|
||||
|
||||
func (m *Messages) getPage(ctx context.Context, key string) (domain.Page[domain.Message], bool) {
|
||||
b, err := m.rdb.Get(ctx, key).Bytes()
|
||||
if err != nil {
|
||||
m.markDown(err)
|
||||
return domain.Page[domain.Message]{}, false
|
||||
}
|
||||
page, err := decodePage(b)
|
||||
return page, err == nil
|
||||
}
|
||||
|
||||
func (m *Messages) sleepFill(ctx context.Context) {
|
||||
if m.opt.FillDelay <= 0 {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-time.After(m.opt.FillDelay):
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}
|
||||
|
||||
func verKey(chatID string) string { return "hc:ver:" + chatID }
|
||||
|
||||
func pageKey(prefix, cursor string, limit int) string {
|
||||
return prefix + ":" + strconv.Itoa(limit) + ":" + cursor
|
||||
}
|
||||
|
||||
func randomVersion() string {
|
||||
var b [8]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
type cachedPage struct {
|
||||
Items []domain.Message `json:"items"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func encodePage(p domain.Page[domain.Message]) ([]byte, error) {
|
||||
return json.Marshal(cachedPage{Items: p.Items, NextCursor: p.NextCursor})
|
||||
}
|
||||
|
||||
func decodePage(b []byte) (domain.Page[domain.Message], error) {
|
||||
var c cachedPage
|
||||
if err := json.Unmarshal(b, &c); err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
return domain.Page[domain.Message]{Items: c.Items, NextCursor: c.NextCursor}, nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package config
|
||||
|
||||
// Верхние границы из контракта: конфигурация может их уменьшить, но не превысить.
|
||||
const (
|
||||
ContractMaxUploadBytes = 10 * 1024 * 1024
|
||||
ContractMaxImagePixels = 40_000_000
|
||||
)
|
||||
|
||||
type S3 struct {
|
||||
Endpoint string
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKeyIDFile string
|
||||
SecretAccessKeyFile string
|
||||
// TimeoutMs — предел на одну операцию с S3. Меньше timeout server балансировщика (15 с):
|
||||
// клиент получает 503 от API, а не 504 от LB.
|
||||
TimeoutMs int
|
||||
}
|
||||
|
||||
type Attachments struct {
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
// MaxConcurrentUploads ограничивает загрузки на одну реплику и тем самым диск под временные
|
||||
// файлы (не больше MaxConcurrentUploads × MaxUploadBytes); сверх него — 429.
|
||||
MaxConcurrentUploads int
|
||||
}
|
||||
|
||||
// MinJanitorGraceSeconds covers the direct ticket lifetime (120s), complete
|
||||
// timeout (60s), and an additional safety margin before orphan deletion.
|
||||
const MinJanitorGraceSeconds = 300
|
||||
|
||||
// Janitor — очиститель объектов без метаданных (cmd/janitor).
|
||||
type Janitor struct {
|
||||
GraceSeconds int
|
||||
IntervalSeconds int
|
||||
// MaxDeletes — сколько объектов без строки допустимо удалить за проход. Больше — признак аварии
|
||||
// (например, БД восстановлена из старой копии), и очиститель ничего не удаляет.
|
||||
MaxDeletes int
|
||||
DryRun bool
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var instanceIDPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type Config struct {
|
||||
Env string
|
||||
Version string
|
||||
InstanceID string
|
||||
|
||||
HTTP HTTP
|
||||
Logger Logger
|
||||
Limits Limits
|
||||
Database Database
|
||||
Cache Cache
|
||||
Session Session
|
||||
|
||||
S3 S3
|
||||
Attachments Attachments
|
||||
Janitor Janitor
|
||||
|
||||
Idempotency Idempotency
|
||||
HistoryCache HistoryCache
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
cfg := defaults()
|
||||
if err := cfg.applyEnv(os.LookupEnv); err != nil {
|
||||
return nil, fmt.Errorf("config: env: %w", err)
|
||||
}
|
||||
if cfg.InstanceID == "" {
|
||||
cfg.InstanceID = defaultInstanceID()
|
||||
}
|
||||
if err := cfg.validate(); err != nil {
|
||||
return nil, fmt.Errorf("config: validate: %w", err)
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func defaults() *Config {
|
||||
return &Config{
|
||||
Env: "lab",
|
||||
Version: "dev",
|
||||
HTTP: HTTP{
|
||||
Addr: "0.0.0.0:8080",
|
||||
ReadTimeoutMs: 10000,
|
||||
WriteTimeoutMs: 10000,
|
||||
IdleTimeoutMs: 60000,
|
||||
ShutdownTimeoutMs: 10000,
|
||||
ShutdownDrainMs: 3000,
|
||||
},
|
||||
Logger: Logger{Level: "info"},
|
||||
Limits: Limits{
|
||||
MaxBodyBytes: 64 * 1024,
|
||||
MaxInFlight: 64,
|
||||
MaxMessagesGlobal: 100000,
|
||||
MaxHeapBytes: 256 * 1024 * 1024,
|
||||
},
|
||||
Database: Database{
|
||||
MaxConns: 10,
|
||||
ConnectTimeoutMs: 5000,
|
||||
QueryTimeoutMs: 3000,
|
||||
},
|
||||
Cache: Cache{
|
||||
PoolSize: 20,
|
||||
TimeoutMs: 1000,
|
||||
},
|
||||
Session: Session{Store: "valkey", TTLSeconds: 3600},
|
||||
S3: S3{
|
||||
Endpoint: "http://s3:9000",
|
||||
Region: "us-east-1",
|
||||
Bucket: "messenger-attachments",
|
||||
TimeoutMs: 8000,
|
||||
},
|
||||
Attachments: Attachments{
|
||||
MaxUploadBytes: ContractMaxUploadBytes,
|
||||
MaxImagePixels: ContractMaxImagePixels,
|
||||
MaxConcurrentUploads: 16,
|
||||
},
|
||||
Janitor: Janitor{GraceSeconds: 3600, IntervalSeconds: 600, MaxDeletes: 1000},
|
||||
Idempotency: Idempotency{TTLSeconds: MinIdempotencyTTLSeconds},
|
||||
HistoryCache: HistoryCache{
|
||||
Mode: "off",
|
||||
PageTTLSeconds: 30,
|
||||
TimeoutMs: 200,
|
||||
PoolSize: 20,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// defaultInstanceID — hostname: в Docker это короткий ID контейнера, поэтому ответ
|
||||
// можно сопоставить с конкретным контейнером. Значение неизменно на всю жизнь процесса.
|
||||
func defaultInstanceID() string {
|
||||
if h, err := os.Hostname(); err == nil && instanceIDPattern.MatchString(h) {
|
||||
return h
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
|
||||
func (c *Config) validate() error {
|
||||
if !instanceIDPattern.MatchString(c.InstanceID) {
|
||||
return fmt.Errorf("APP_INSTANCE_ID must match %s", instanceIDPattern)
|
||||
}
|
||||
if strings.TrimSpace(c.Env) == "" {
|
||||
return errors.New("env is required")
|
||||
}
|
||||
if strings.TrimSpace(c.Version) == "" {
|
||||
return errors.New("version is required")
|
||||
}
|
||||
if strings.TrimSpace(c.HTTP.Addr) == "" {
|
||||
return errors.New("http.addr is required")
|
||||
}
|
||||
if c.HTTP.ShutdownTimeoutMs <= 0 || c.HTTP.ShutdownTimeoutMs > 10000 {
|
||||
return fmt.Errorf("APP_SHUTDOWN_TIMEOUT_MS must be in (0, 10000], got %d", c.HTTP.ShutdownTimeoutMs)
|
||||
}
|
||||
if c.HTTP.ShutdownDrainMs < 0 || c.HTTP.ShutdownDrainMs > 10000 {
|
||||
return fmt.Errorf("APP_SHUTDOWN_DRAIN_MS must be in [0, 10000], got %d", c.HTTP.ShutdownDrainMs)
|
||||
}
|
||||
if c.HTTP.ReadTimeoutMs <= 0 {
|
||||
return fmt.Errorf("APP_READ_TIMEOUT_MS must be > 0, got %d", c.HTTP.ReadTimeoutMs)
|
||||
}
|
||||
if c.HTTP.WriteTimeoutMs <= 0 {
|
||||
return fmt.Errorf("APP_WRITE_TIMEOUT_MS must be > 0, got %d", c.HTTP.WriteTimeoutMs)
|
||||
}
|
||||
if c.HTTP.IdleTimeoutMs <= 0 {
|
||||
return fmt.Errorf("APP_IDLE_TIMEOUT_MS must be > 0, got %d", c.HTTP.IdleTimeoutMs)
|
||||
}
|
||||
|
||||
if c.Limits.MaxBodyBytes <= 0 {
|
||||
return fmt.Errorf("APP_MAX_BODY_BYTES must be > 0, got %d", c.Limits.MaxBodyBytes)
|
||||
}
|
||||
if c.Limits.MaxInFlight <= 0 {
|
||||
return fmt.Errorf("APP_MAX_INFLIGHT must be > 0, got %d", c.Limits.MaxInFlight)
|
||||
}
|
||||
if c.Limits.MaxMessagesGlobal <= 0 {
|
||||
return fmt.Errorf("APP_MAX_MESSAGES must be > 0, got %d", c.Limits.MaxMessagesGlobal)
|
||||
}
|
||||
if c.Limits.MaxHeapBytes == 0 {
|
||||
return errors.New("APP_MAX_HEAP_BYTES must be > 0")
|
||||
}
|
||||
|
||||
if c.S3.TimeoutMs <= 0 {
|
||||
return fmt.Errorf("S3_TIMEOUT_MS must be > 0, got %d", c.S3.TimeoutMs)
|
||||
}
|
||||
if c.Attachments.MaxUploadBytes <= 0 || c.Attachments.MaxUploadBytes > ContractMaxUploadBytes {
|
||||
return fmt.Errorf("MAX_UPLOAD_BYTES must be in (0, %d], got %d", ContractMaxUploadBytes, c.Attachments.MaxUploadBytes)
|
||||
}
|
||||
if c.Attachments.MaxImagePixels <= 0 || c.Attachments.MaxImagePixels > ContractMaxImagePixels {
|
||||
return fmt.Errorf("MAX_IMAGE_PIXELS must be in (0, %d], got %d", ContractMaxImagePixels, c.Attachments.MaxImagePixels)
|
||||
}
|
||||
if c.Attachments.MaxConcurrentUploads <= 0 {
|
||||
return fmt.Errorf("MAX_CONCURRENT_UPLOADS must be > 0, got %d", c.Attachments.MaxConcurrentUploads)
|
||||
}
|
||||
|
||||
if c.Janitor.GraceSeconds < MinJanitorGraceSeconds {
|
||||
return fmt.Errorf("JANITOR_GRACE_SECONDS must be >= %d, got %d", MinJanitorGraceSeconds, c.Janitor.GraceSeconds)
|
||||
}
|
||||
if c.Janitor.IntervalSeconds <= 0 {
|
||||
return fmt.Errorf("JANITOR_INTERVAL_SECONDS must be > 0, got %d", c.Janitor.IntervalSeconds)
|
||||
}
|
||||
if c.Janitor.MaxDeletes <= 0 {
|
||||
return fmt.Errorf("JANITOR_MAX_DELETES must be > 0, got %d", c.Janitor.MaxDeletes)
|
||||
}
|
||||
|
||||
if c.Database.MaxConns <= 0 {
|
||||
return fmt.Errorf("DB_MAX_CONNS must be > 0, got %d", c.Database.MaxConns)
|
||||
}
|
||||
if c.Database.ConnectTimeoutMs <= 0 {
|
||||
return fmt.Errorf("DB_CONNECT_TIMEOUT_MS must be > 0, got %d", c.Database.ConnectTimeoutMs)
|
||||
}
|
||||
if c.Database.QueryTimeoutMs <= 0 {
|
||||
return fmt.Errorf("DB_QUERY_TIMEOUT_MS must be > 0, got %d", c.Database.QueryTimeoutMs)
|
||||
}
|
||||
if c.Cache.PoolSize <= 0 {
|
||||
return fmt.Errorf("CACHE_POOL_SIZE must be > 0, got %d", c.Cache.PoolSize)
|
||||
}
|
||||
if c.Cache.TimeoutMs <= 0 {
|
||||
return fmt.Errorf("CACHE_TIMEOUT_MS must be > 0, got %d", c.Cache.TimeoutMs)
|
||||
}
|
||||
switch c.HistoryCache.Mode {
|
||||
case "off", "naive", "safe":
|
||||
default:
|
||||
return fmt.Errorf("HISTORY_CACHE must be off|naive|safe, got %q", c.HistoryCache.Mode)
|
||||
}
|
||||
if c.HistoryCache.PageTTLSeconds <= 0 {
|
||||
return fmt.Errorf("HISTORY_CACHE_TTL_SECONDS must be > 0, got %d", c.HistoryCache.PageTTLSeconds)
|
||||
}
|
||||
if c.HistoryCache.TimeoutMs <= 0 || c.HistoryCache.PoolSize <= 0 {
|
||||
return errors.New("HISTORY_CACHE_TIMEOUT_MS and HISTORY_CACHE_POOL_SIZE must be > 0")
|
||||
}
|
||||
if c.HistoryCache.FillDelayMs < 0 || c.HistoryCache.FillDelayMs > 1000 {
|
||||
return fmt.Errorf("HISTORY_CACHE_FILL_DELAY_MS must be in [0, 1000], got %d", c.HistoryCache.FillDelayMs)
|
||||
}
|
||||
// Реализовано одно хранилище сессий; иное значение — ошибка конфигурации, а не тихий выбор.
|
||||
if c.Session.Store != "valkey" {
|
||||
return fmt.Errorf("SESSION_STORE must be valkey (the only implemented session store), got %q", c.Session.Store)
|
||||
}
|
||||
if c.Idempotency.TTLSeconds < MinIdempotencyTTLSeconds {
|
||||
return fmt.Errorf("IDEMPOTENCY_TTL_SECONDS must be >= %d, got %d", MinIdempotencyTTLSeconds, c.Idempotency.TTLSeconds)
|
||||
}
|
||||
if c.Session.TTLSeconds <= 0 {
|
||||
return fmt.Errorf("SESSION_TTL_SECONDS must be > 0, got %d", c.Session.TTLSeconds)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package config
|
||||
|
||||
type Database struct {
|
||||
URLFile string
|
||||
URL string
|
||||
MaxConns int32
|
||||
ConnectTimeoutMs int
|
||||
QueryTimeoutMs int
|
||||
// EnableBitmapScan: по умолчанию выключено. Для чата, которого ещё нет в статистике,
|
||||
// планировщик может ожидать почти пустой результат и выбрать чтение всего чата с сортировкой.
|
||||
// Это гипотеза: замеров, подтверждающих выигрыш, в evidence нет. Флаг нужен для сравнения.
|
||||
EnableBitmapScan bool
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (c *Config) applyEnv(lookup func(string) (string, bool)) error {
|
||||
get := func(key string) (string, bool) {
|
||||
v, ok := lookup(key)
|
||||
v = strings.TrimSpace(v)
|
||||
return v, ok && v != ""
|
||||
}
|
||||
|
||||
if v, ok := get("APP_ENV"); ok {
|
||||
c.Env = v
|
||||
}
|
||||
if v, ok := get("APP_VERSION"); ok {
|
||||
c.Version = v
|
||||
}
|
||||
if v, ok := get("APP_INSTANCE_ID"); ok {
|
||||
c.InstanceID = v
|
||||
}
|
||||
if v, ok := get("APP_LOG_LEVEL"); ok {
|
||||
c.Logger.Level = v
|
||||
}
|
||||
if v, ok := get("DATABASE_URL_FILE"); ok {
|
||||
c.Database.URLFile = v
|
||||
}
|
||||
if v, ok := get("DATABASE_URL"); ok {
|
||||
c.Database.URL = v
|
||||
}
|
||||
if v, ok := get("CACHE_URL_FILE"); ok {
|
||||
c.Cache.URLFile = v
|
||||
}
|
||||
if v, ok := get("CACHE_URL"); ok {
|
||||
c.Cache.URL = v
|
||||
}
|
||||
if v, ok := get("SESSION_STORE"); ok {
|
||||
c.Session.Store = strings.ToLower(v)
|
||||
}
|
||||
if v, ok := get("S3_ENDPOINT"); ok {
|
||||
c.S3.Endpoint = v
|
||||
}
|
||||
if v, ok := get("S3_REGION"); ok {
|
||||
c.S3.Region = v
|
||||
}
|
||||
if v, ok := get("S3_BUCKET"); ok {
|
||||
c.S3.Bucket = v
|
||||
}
|
||||
if v, ok := get("S3_ACCESS_KEY_ID_FILE"); ok {
|
||||
c.S3.AccessKeyIDFile = v
|
||||
}
|
||||
if v, ok := get("S3_SECRET_ACCESS_KEY_FILE"); ok {
|
||||
c.S3.SecretAccessKeyFile = v
|
||||
}
|
||||
if v, ok := get("HISTORY_CACHE"); ok {
|
||||
c.HistoryCache.Mode = strings.ToLower(v)
|
||||
}
|
||||
if v, ok := get("HISTORY_CACHE_URL_FILE"); ok {
|
||||
c.HistoryCache.URLFile = v
|
||||
}
|
||||
if v, ok := get("HISTORY_CACHE_URL"); ok {
|
||||
c.HistoryCache.URL = v
|
||||
}
|
||||
|
||||
if v, ok := get("JANITOR_DRY_RUN"); ok {
|
||||
dryRun, err := strconv.ParseBool(v)
|
||||
if err != nil {
|
||||
return fmt.Errorf("JANITOR_DRY_RUN: not a boolean: %q", v)
|
||||
}
|
||||
c.Janitor.DryRun = dryRun
|
||||
}
|
||||
|
||||
host, port, err := net.SplitHostPort(c.HTTP.Addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("default addr %q: %w", c.HTTP.Addr, err)
|
||||
}
|
||||
if v, ok := get("APP_HOST"); ok {
|
||||
host = v
|
||||
}
|
||||
if v, ok := get("APP_PORT"); ok {
|
||||
port = v
|
||||
}
|
||||
if n, err := strconv.Atoi(port); err != nil || n < 1 || n > 65535 {
|
||||
return fmt.Errorf("APP_PORT must be in [1, 65535], got %q", port)
|
||||
}
|
||||
c.HTTP.Addr = net.JoinHostPort(host, port)
|
||||
|
||||
ints := []struct {
|
||||
key string
|
||||
dst *int
|
||||
}{
|
||||
{"APP_READ_TIMEOUT_MS", &c.HTTP.ReadTimeoutMs},
|
||||
{"APP_WRITE_TIMEOUT_MS", &c.HTTP.WriteTimeoutMs},
|
||||
{"APP_IDLE_TIMEOUT_MS", &c.HTTP.IdleTimeoutMs},
|
||||
{"APP_SHUTDOWN_TIMEOUT_MS", &c.HTTP.ShutdownTimeoutMs},
|
||||
{"APP_SHUTDOWN_DRAIN_MS", &c.HTTP.ShutdownDrainMs},
|
||||
{"APP_MAX_INFLIGHT", &c.Limits.MaxInFlight},
|
||||
{"APP_MAX_MESSAGES", &c.Limits.MaxMessagesGlobal},
|
||||
{"DB_CONNECT_TIMEOUT_MS", &c.Database.ConnectTimeoutMs},
|
||||
{"DB_QUERY_TIMEOUT_MS", &c.Database.QueryTimeoutMs},
|
||||
{"S3_TIMEOUT_MS", &c.S3.TimeoutMs},
|
||||
{"MAX_CONCURRENT_UPLOADS", &c.Attachments.MaxConcurrentUploads},
|
||||
{"JANITOR_GRACE_SECONDS", &c.Janitor.GraceSeconds},
|
||||
{"JANITOR_INTERVAL_SECONDS", &c.Janitor.IntervalSeconds},
|
||||
{"JANITOR_MAX_DELETES", &c.Janitor.MaxDeletes},
|
||||
{"CACHE_POOL_SIZE", &c.Cache.PoolSize},
|
||||
{"CACHE_TIMEOUT_MS", &c.Cache.TimeoutMs},
|
||||
{"SESSION_TTL_SECONDS", &c.Session.TTLSeconds},
|
||||
{"IDEMPOTENCY_TTL_SECONDS", &c.Idempotency.TTLSeconds},
|
||||
{"HISTORY_CACHE_TTL_SECONDS", &c.HistoryCache.PageTTLSeconds},
|
||||
{"HISTORY_CACHE_TIMEOUT_MS", &c.HistoryCache.TimeoutMs},
|
||||
{"HISTORY_CACHE_POOL_SIZE", &c.HistoryCache.PoolSize},
|
||||
{"HISTORY_CACHE_FILL_DELAY_MS", &c.HistoryCache.FillDelayMs},
|
||||
}
|
||||
for _, it := range ints {
|
||||
v, ok := get(it.key)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: not an integer: %q", it.key, v)
|
||||
}
|
||||
*it.dst = n
|
||||
}
|
||||
|
||||
if v, ok := get("APP_MAX_BODY_BYTES"); ok {
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("APP_MAX_BODY_BYTES: not an integer: %q", v)
|
||||
}
|
||||
c.Limits.MaxBodyBytes = n
|
||||
}
|
||||
for _, it := range []struct {
|
||||
key string
|
||||
dst *int64
|
||||
}{
|
||||
{"MAX_UPLOAD_BYTES", &c.Attachments.MaxUploadBytes},
|
||||
{"MAX_IMAGE_PIXELS", &c.Attachments.MaxImagePixels},
|
||||
} {
|
||||
if v, ok := get(it.key); ok {
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: not an integer: %q", it.key, v)
|
||||
}
|
||||
*it.dst = n
|
||||
}
|
||||
}
|
||||
if v, ok := get("DB_MAX_CONNS"); ok {
|
||||
n, err := strconv.ParseInt(v, 10, 32)
|
||||
if err != nil {
|
||||
return fmt.Errorf("DB_MAX_CONNS: not an integer: %q", v)
|
||||
}
|
||||
c.Database.MaxConns = int32(n)
|
||||
}
|
||||
if v, ok := get("DB_ENABLE_BITMAPSCAN"); ok {
|
||||
b, err := strconv.ParseBool(v)
|
||||
if err != nil {
|
||||
return fmt.Errorf("DB_ENABLE_BITMAPSCAN: not a boolean: %q", v)
|
||||
}
|
||||
c.Database.EnableBitmapScan = b
|
||||
}
|
||||
if v, ok := get("APP_MAX_HEAP_BYTES"); ok {
|
||||
n, err := strconv.ParseUint(v, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("APP_MAX_HEAP_BYTES: not a non-negative integer: %q", v)
|
||||
}
|
||||
c.Limits.MaxHeapBytes = n
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package config
|
||||
|
||||
type HistoryCache struct {
|
||||
Mode string
|
||||
URLFile string
|
||||
URL string
|
||||
PageTTLSeconds int
|
||||
TimeoutMs int
|
||||
PoolSize int
|
||||
FillDelayMs int
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package config
|
||||
|
||||
type HTTP struct {
|
||||
Addr string
|
||||
ReadTimeoutMs int
|
||||
WriteTimeoutMs int
|
||||
IdleTimeoutMs int
|
||||
ShutdownTimeoutMs int
|
||||
// ShutdownDrainMs — сколько после SIGTERM обслуживать запросы, отвечая на readiness 503,
|
||||
// чтобы балансировщик успел вывести реплику. Должно быть больше времени его обнаружения.
|
||||
ShutdownDrainMs int
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package config
|
||||
|
||||
// MinIdempotencyTTLSeconds — контракт требует хранить результат не менее 24 часов.
|
||||
const MinIdempotencyTTLSeconds = 86400
|
||||
|
||||
type Idempotency struct {
|
||||
TTLSeconds int
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package config
|
||||
|
||||
type Limits struct {
|
||||
MaxBodyBytes int64
|
||||
MaxInFlight int
|
||||
MaxMessagesGlobal int
|
||||
MaxHeapBytes uint64
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package config
|
||||
|
||||
type Logger struct {
|
||||
Level string
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package config
|
||||
|
||||
type Session struct {
|
||||
Store string
|
||||
TTLSeconds int
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
URLFile string
|
||||
URL string
|
||||
PoolSize int
|
||||
TimeoutMs int
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
// StatusReady — единственное состояние вложения в lab4: метаданные появляются только после
|
||||
// сохранения оригинала. Асинхронные состояния добавляются с lab5.
|
||||
const StatusReady = "ready"
|
||||
|
||||
const (
|
||||
ContentTypePNG = "image/png"
|
||||
ContentTypeJPEG = "image/jpeg"
|
||||
)
|
||||
|
||||
type Variant struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
type Attachment struct {
|
||||
Variants []Variant
|
||||
Thumbnail Variant
|
||||
ErrorCode *string
|
||||
ID string
|
||||
ChatID string
|
||||
OwnerID string
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
// ObjectKey — внутренний ключ в bucket, назначает сервер. В публичный API не попадает.
|
||||
ObjectKey string
|
||||
Status string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Chat struct {
|
||||
ID string
|
||||
Title string
|
||||
MemberIDs []string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
|
||||
ErrConflict = errors.New("conflict")
|
||||
|
||||
// ErrIdempotencyConflict — ключ уже использован с другим телом запроса.
|
||||
ErrIdempotencyConflict = fmt.Errorf("idempotency key reused with different request: %w", ErrConflict)
|
||||
|
||||
ErrInvalidArgument = errors.New("invalid argument")
|
||||
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
|
||||
ErrPayloadTooLarge = errors.New("payload too large")
|
||||
|
||||
ErrRateLimited = errors.New("rate limited")
|
||||
|
||||
ErrUnsupportedMedia = errors.New("unsupported media")
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Message struct {
|
||||
ID string
|
||||
ChatID string
|
||||
AuthorID string
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
// AttachmentIDs — вложения этого чата в порядке из запроса; без вложений пусто.
|
||||
AttachmentIDs []string
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Page[T any] struct {
|
||||
Items []T
|
||||
NextCursor string
|
||||
}
|
||||
|
||||
type Cursor struct {
|
||||
CreatedAt time.Time `json:"t"`
|
||||
ID string `json:"i"`
|
||||
Scope string `json:"s,omitempty"`
|
||||
}
|
||||
|
||||
func (c Cursor) IsZero() bool {
|
||||
return c.ID == "" && c.CreatedAt.IsZero()
|
||||
}
|
||||
|
||||
func (c Cursor) Less(createdAt time.Time, id string) bool {
|
||||
if c.CreatedAt.Before(createdAt) {
|
||||
return true
|
||||
}
|
||||
if c.CreatedAt.After(createdAt) {
|
||||
return false
|
||||
}
|
||||
return c.ID < id
|
||||
}
|
||||
|
||||
func EncodeCursor(c Cursor) string {
|
||||
if c.IsZero() {
|
||||
return ""
|
||||
}
|
||||
b, _ := json.Marshal(c)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
func DecodeCursor(s string) (Cursor, error) {
|
||||
if s == "" {
|
||||
return Cursor{}, nil
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return Cursor{}, ErrInvalidArgument
|
||||
}
|
||||
var c Cursor
|
||||
if err := json.Unmarshal(raw, &c); err != nil {
|
||||
return Cursor{}, ErrInvalidArgument
|
||||
}
|
||||
|
||||
if c.CreatedAt.IsZero() || c.Scope == "" {
|
||||
return Cursor{}, ErrInvalidArgument
|
||||
}
|
||||
if _, err := uuid.Parse(c.ID); err != nil || len(c.ID) != 36 {
|
||||
return Cursor{}, ErrInvalidArgument
|
||||
}
|
||||
if EncodeCursor(c) != s {
|
||||
return Cursor{}, ErrInvalidArgument
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Session 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,128 @@
|
||||
// Package imagecheck определяет тип изображения по содержимому и проверяет, что файл целый.
|
||||
package imagecheck
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrUnsupported — не PNG/JPEG либо файл повреждён.
|
||||
ErrUnsupported = errors.New("imagecheck: not a valid PNG or JPEG")
|
||||
// ErrTooManyPixels — размеры из заголовка превышают лимит.
|
||||
ErrTooManyPixels = errors.New("imagecheck: too many pixels")
|
||||
// ErrBusy — очередь на декодирование не подошла за decodeWait.
|
||||
ErrBusy = errors.New("imagecheck: decoder is busy")
|
||||
)
|
||||
|
||||
var (
|
||||
pngMagic = []byte("\x89PNG\r\n\x1a\n")
|
||||
jpegMagic = []byte{0xff, 0xd8, 0xff}
|
||||
)
|
||||
|
||||
const (
|
||||
// decodeWait ограничивает ожидание очереди на декодирование. Вместе с записью в S3 и БД ответ
|
||||
// должен уложиться в timeout server балансировщика (15 с): лучше честный 429, чем 504.
|
||||
decodeWait = 5 * time.Second
|
||||
// Файл читается с диска маленькими порциями; буфер убирает лишние системные вызовы.
|
||||
readBuffer = 64 << 10
|
||||
)
|
||||
|
||||
type format struct {
|
||||
contentType string
|
||||
config func(io.Reader) (image.Config, error)
|
||||
decode func(io.Reader) (image.Image, error)
|
||||
}
|
||||
|
||||
func detect(head []byte) (format, bool) {
|
||||
switch {
|
||||
case bytes.HasPrefix(head, pngMagic):
|
||||
return format{domain.ContentTypePNG, png.DecodeConfig, png.Decode}, true
|
||||
case bytes.HasPrefix(head, jpegMagic):
|
||||
return format{domain.ContentTypeJPEG, jpeg.DecodeConfig, jpeg.Decode}, true
|
||||
}
|
||||
return format{}, false
|
||||
}
|
||||
|
||||
func read(r io.ReadSeeker) (format, error) {
|
||||
if _, err := r.Seek(0, io.SeekStart); err != nil {
|
||||
return format{}, err
|
||||
}
|
||||
head := make([]byte, len(pngMagic))
|
||||
n, err := io.ReadFull(r, head)
|
||||
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return format{}, err
|
||||
}
|
||||
f, ok := detect(head[:n])
|
||||
if !ok {
|
||||
return format{}, ErrUnsupported
|
||||
}
|
||||
if _, err := r.Seek(0, io.SeekStart); err != nil {
|
||||
return format{}, err
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// Checker ограничивает расход памяти на проверку: размеры читаются из заголовка без распаковки,
|
||||
// а полное декодирование выполняется только в пределах лимита пикселей и по одному за раз.
|
||||
// Декодирование 40 Мп занимает сотни мегабайт, поэтому параллелить его нельзя.
|
||||
type Checker struct {
|
||||
maxPixels int64
|
||||
decoding chan struct{}
|
||||
}
|
||||
|
||||
func New(maxPixels int64) *Checker {
|
||||
return &Checker{maxPixels: maxPixels, decoding: make(chan struct{}, 1)}
|
||||
}
|
||||
|
||||
// Inspect определяет истинный Content-Type по сигнатуре и проверяет размеры из заголовка. Пиксели
|
||||
// не распаковываются, поэтому «бомба» и подмена типа отклоняются почти без затрат.
|
||||
func (c *Checker) Inspect(r io.ReadSeeker) (string, error) {
|
||||
f, err := read(r)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cfg, err := f.config(bufio.NewReaderSize(r, readBuffer))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: header", ErrUnsupported)
|
||||
}
|
||||
if cfg.Width <= 0 || cfg.Height <= 0 {
|
||||
return "", fmt.Errorf("%w: empty image", ErrUnsupported)
|
||||
}
|
||||
if int64(cfg.Width) > c.maxPixels || int64(cfg.Width)*int64(cfg.Height) > c.maxPixels {
|
||||
return "", ErrTooManyPixels
|
||||
}
|
||||
return f.contentType, nil
|
||||
}
|
||||
|
||||
// Decode полностью декодирует файл, уже прошедший Inspect. Результат не нужен: важно, что файл целый.
|
||||
func (c *Checker) Decode(ctx context.Context, r io.ReadSeeker) error {
|
||||
timer := time.NewTimer(decodeWait)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case c.decoding <- struct{}{}:
|
||||
defer func() { <-c.decoding }()
|
||||
case <-timer.C:
|
||||
return ErrBusy
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
f, err := read(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := f.decode(bufio.NewReaderSize(r, readBuffer)); err != nil {
|
||||
return fmt.Errorf("%w: body", ErrUnsupported)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func New(level, env, version string) (*slog.Logger, error) {
|
||||
lvl, err := parseLevel(level)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return build(os.Stdout, lvl, env, version), nil
|
||||
}
|
||||
|
||||
func build(w io.Writer, lvl slog.Level, env, version string) *slog.Logger {
|
||||
handler := slog.NewJSONHandler(w, &slog.HandlerOptions{
|
||||
Level: lvl,
|
||||
ReplaceAttr: forceUTCTime,
|
||||
})
|
||||
return slog.New(handler).With(
|
||||
slog.String("service", "messenger"),
|
||||
slog.String("env", env),
|
||||
slog.String("version", version),
|
||||
)
|
||||
}
|
||||
|
||||
func forceUTCTime(_ []string, a slog.Attr) slog.Attr {
|
||||
if a.Value.Kind() == slog.KindTime {
|
||||
a.Value = slog.TimeValue(a.Value.Time().UTC())
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func parseLevel(s string) (slog.Level, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(s)) {
|
||||
case "", "info":
|
||||
return slog.LevelInfo, nil
|
||||
case "debug":
|
||||
return slog.LevelDebug, nil
|
||||
case "warn", "warning":
|
||||
return slog.LevelWarn, nil
|
||||
case "error":
|
||||
return slog.LevelError, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("logging: unknown level %q (want debug|info|warn|error)", s)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
// Memory — хранилище для модульных тестов. В работающем приложении не используется.
|
||||
type Memory struct {
|
||||
mu sync.Mutex
|
||||
objects map[string][]byte
|
||||
modified map[string]time.Time
|
||||
// Down имитирует недоступность S3.
|
||||
Down atomic.Bool
|
||||
}
|
||||
|
||||
var (
|
||||
_ Store = (*Memory)(nil)
|
||||
_ Lister = (*Memory)(nil)
|
||||
)
|
||||
|
||||
func NewMemory() *Memory {
|
||||
return &Memory{objects: make(map[string][]byte), modified: make(map[string]time.Time)}
|
||||
}
|
||||
|
||||
func (m *Memory) check() error {
|
||||
if m.Down.Load() {
|
||||
return fmt.Errorf("%w: s3 down", domain.ErrUnavailable)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Put(_ context.Context, key, _ string, body io.Reader, size int64) error {
|
||||
if err := m.check(); err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := io.ReadAll(body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: s3 put: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
if int64(len(data)) != size {
|
||||
return fmt.Errorf("%w: s3 put: got %d of %d bytes", domain.ErrUnavailable, len(data), size)
|
||||
}
|
||||
m.PutAt(key, data, time.Now())
|
||||
return nil
|
||||
}
|
||||
|
||||
// PutAt кладёт объект с заданным временем: так тест получает объект нужного возраста.
|
||||
func (m *Memory) PutAt(key string, data []byte, at time.Time) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.objects[key] = bytes.Clone(data)
|
||||
m.modified[key] = at
|
||||
}
|
||||
|
||||
func (m *Memory) List(_ context.Context, prefix string, visit func(ObjectInfo) error) error {
|
||||
if err := m.check(); err != nil {
|
||||
return err
|
||||
}
|
||||
m.mu.Lock()
|
||||
infos := make([]ObjectInfo, 0, len(m.objects))
|
||||
for key := range m.objects {
|
||||
if strings.HasPrefix(key, prefix) {
|
||||
infos = append(infos, ObjectInfo{Key: key, LastModified: m.modified[key]})
|
||||
}
|
||||
}
|
||||
m.mu.Unlock()
|
||||
for _, info := range infos {
|
||||
if err := visit(info); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Get(_ context.Context, key string) (io.ReadCloser, int64, error) {
|
||||
if err := m.check(); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
data, ok := m.objects[key]
|
||||
if !ok {
|
||||
return nil, 0, ErrNotFound
|
||||
}
|
||||
return io.NopCloser(bytes.NewReader(data)), int64(len(data)), nil
|
||||
}
|
||||
|
||||
func (m *Memory) Delete(_ context.Context, key string) error {
|
||||
if err := m.check(); err != nil {
|
||||
return err
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.objects, key)
|
||||
delete(m.modified, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Keys возвращает ключи объектов для проверок в тестах.
|
||||
func (m *Memory) Keys() []string {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
out := make([]string, 0, len(m.objects))
|
||||
for k := range m.objects {
|
||||
out = append(out, k)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Package objectstore — хранилище байтов вложений. Интерфейс не зависит от конкретного сервера.
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrNotFound — в bucket нет объекта. Метаданные пишутся после объекта, поэтому для существующего
|
||||
// вложения это нарушение согласованности, а не обычная ошибка клиента.
|
||||
var ErrNotFound = errors.New("objectstore: object not found")
|
||||
|
||||
// ObjectInfo — то, что очистителю нужно знать об объекте из листинга.
|
||||
type ObjectInfo struct {
|
||||
Key string
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
type Store interface {
|
||||
// Put передаёт объект потоком: size байт из body, без чтения всего файла в память.
|
||||
Put(ctx context.Context, key, contentType string, body io.Reader, size int64) error
|
||||
// Get возвращает поток и размер объекта. Поток обязательно закрыть.
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, int64, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
}
|
||||
|
||||
// Lister обходит объекты bucket. Право на листинг есть только у очистителя, поэтому метод вынесен
|
||||
// из Store: API не может и не должно перечислять объекты.
|
||||
type Lister interface {
|
||||
// List вызывает visit для каждого объекта с заданным префиксом.
|
||||
List(ctx context.Context, prefix string, visit func(ObjectInfo) error) error
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
// S3 работает с любым S3-совместимым сервером; на стенде это SeaweedFS.
|
||||
type S3 struct {
|
||||
signingCreds *credentials.Credentials
|
||||
region string
|
||||
ticketKey []byte
|
||||
client *minio.Client
|
||||
core minio.Core
|
||||
endpoint string
|
||||
bucket string
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
var (
|
||||
_ Store = (*S3)(nil)
|
||||
_ Lister = (*S3)(nil)
|
||||
)
|
||||
|
||||
// NewS3 только готовит клиента и не обращается к серверу: недоступность S3 при запуске не мешает
|
||||
// реплике обслуживать пользователей и сообщения.
|
||||
func NewS3(cfg config.S3) (*S3, error) {
|
||||
u, err := url.Parse(cfg.Endpoint)
|
||||
if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
|
||||
return nil, errors.New("objectstore: S3_ENDPOINT must be http(s)://host:port")
|
||||
}
|
||||
id, err := readSecret("S3_ACCESS_KEY_ID_FILE", cfg.AccessKeyIDFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
secret, err := readSecret("S3_SECRET_ACCESS_KEY_FILE", cfg.SecretAccessKeyFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client, err := minio.New(u.Host, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(id, secret, ""),
|
||||
Secure: u.Scheme == "https",
|
||||
Region: cfg.Region,
|
||||
BucketLookup: minio.BucketLookupPath,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("objectstore: client: %w", err)
|
||||
}
|
||||
return &S3{
|
||||
signingCreds: credentials.NewStaticV4(id, secret, ""),
|
||||
region: cfg.Region,
|
||||
ticketKey: []byte(secret),
|
||||
client: client,
|
||||
core: minio.Core{Client: client},
|
||||
endpoint: cfg.Endpoint,
|
||||
bucket: cfg.Bucket,
|
||||
timeout: time.Duration(cfg.TimeoutMs) * time.Millisecond,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func readSecret(name, path string) (string, error) {
|
||||
if path == "" {
|
||||
return "", fmt.Errorf("objectstore: %s is required", name)
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("objectstore: read %s: %w", name, err)
|
||||
}
|
||||
v := strings.TrimSpace(string(b))
|
||||
if v == "" {
|
||||
return "", fmt.Errorf("objectstore: %s is empty", name)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// unavailable скрывает детали S3 от клиента: наружу уходит только 503.
|
||||
func unavailable(op string, err error) error {
|
||||
return fmt.Errorf("%w: s3 %s: %v", domain.ErrUnavailable, op, err)
|
||||
}
|
||||
|
||||
// Put отправляет объект одним запросом и не буферизует его. Multipart выключен намеренно: при обрыве
|
||||
// одиночного PUT объект не появляется, а незавершённых multipart-загрузок, которые надо отдельно
|
||||
// искать и отменять, просто не существует.
|
||||
func (s *S3) Put(ctx context.Context, key, contentType string, body io.Reader, size int64) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
info, err := s.client.PutObject(ctx, s.bucket, key, body, size,
|
||||
minio.PutObjectOptions{ContentType: contentType, DisableMultipart: true})
|
||||
if err != nil {
|
||||
return unavailable("put", err)
|
||||
}
|
||||
if info.Size != size {
|
||||
return unavailable("put", fmt.Errorf("stored %d of %d bytes", info.Size, size))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// List постранично обходит bucket; размер страницы задаёт сервер, в памяти одна страница.
|
||||
func (s *S3) List(ctx context.Context, prefix string, visit func(ObjectInfo) error) error {
|
||||
// Отмена нужна, чтобы при раннем выходе остановить горутину листинга клиента S3.
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
for object := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
|
||||
if object.Err != nil {
|
||||
return unavailable("list", object.Err)
|
||||
}
|
||||
if err := visit(ObjectInfo{Key: object.Key, LastModified: object.LastModified}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, int64, error) {
|
||||
// Таймаут нужен только на получение ответа: чтение потока ограничивает родительский контекст.
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
timer := time.AfterFunc(s.timeout, cancel)
|
||||
body, info, _, err := s.core.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
timer.Stop()
|
||||
if err != nil {
|
||||
cancel()
|
||||
if minio.ToErrorResponse(err).Code == "NoSuchKey" {
|
||||
return nil, 0, ErrNotFound
|
||||
}
|
||||
return nil, 0, unavailable("get", err)
|
||||
}
|
||||
return &cancelOnClose{ReadCloser: body, cancel: cancel}, info.Size, nil
|
||||
}
|
||||
|
||||
type cancelOnClose struct {
|
||||
io.ReadCloser
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (c *cancelOnClose) Close() error {
|
||||
defer c.cancel()
|
||||
return c.ReadCloser.Close()
|
||||
}
|
||||
|
||||
func (s *S3) Delete(ctx context.Context, key string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
|
||||
return unavailable("delete", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnsureBucket создаёт bucket, если его нет. Повторный запуск ничего не меняет и не трогает объекты.
|
||||
func (s *S3) EnsureBucket(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
exists, err := s.client.BucketExists(ctx, s.bucket)
|
||||
if err != nil {
|
||||
return fmt.Errorf("objectstore: bucket exists: %w", err)
|
||||
}
|
||||
if exists {
|
||||
return nil
|
||||
}
|
||||
err = s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{})
|
||||
if err != nil && minio.ToErrorResponse(err).Code != "BucketAlreadyOwnedByYou" {
|
||||
return fmt.Errorf("objectstore: make bucket: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemovePolicy удаляет политику bucket, если она есть, и сообщает, была ли она. Доступ на стенде
|
||||
// определяют только ключи, поэтому любая политика — чужеродное изменение, а не настройка.
|
||||
func (s *S3) RemovePolicy(ctx context.Context) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
policy, err := s.client.GetBucketPolicy(ctx, s.bucket)
|
||||
if err != nil && minio.ToErrorResponse(err).Code != "NoSuchBucketPolicy" {
|
||||
return false, fmt.Errorf("objectstore: get policy: %w", err)
|
||||
}
|
||||
if policy == "" {
|
||||
return false, nil
|
||||
}
|
||||
if err := s.client.SetBucketPolicy(ctx, s.bucket, ""); err != nil {
|
||||
return false, fmt.Errorf("objectstore: remove policy: %w", err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// CheckPrivate делает запрос без подписи и ожидает отказ. Политику bucket никто не задаёт, поэтому
|
||||
// приватность — поведение по умолчанию, а эта проверка не даёт запустить стенд, если это не так.
|
||||
func (s *S3) CheckPrivate(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(s.endpoint, "/")+"/"+s.bucket+"/", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("objectstore: anonymous probe: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusUnauthorized {
|
||||
return fmt.Errorf("objectstore: anonymous listing returned %d, bucket is not private", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UploadMAC uses a separate domain from S3 request signatures. Shared credentials
|
||||
// allow init and complete to run on different replicas without pending DB rows.
|
||||
func (s *S3) UploadMAC(data []byte) []byte {
|
||||
h := hmac.New(sha256.New, s.ticketKey)
|
||||
h.Write([]byte("lab4-upload-ticket-v1\x00"))
|
||||
h.Write(data)
|
||||
return h.Sum(nil)
|
||||
}
|
||||
|
||||
func (s *S3) PresignUpload(ctx context.Context, key, contentType string, size int64) (string, error) {
|
||||
endpoint := os.Getenv("S3_PUBLIC_ENDPOINT")
|
||||
if endpoint == "" {
|
||||
endpoint = s.endpoint
|
||||
}
|
||||
u, err := url.Parse(endpoint)
|
||||
if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
|
||||
return "", domain.ErrUnavailable
|
||||
}
|
||||
// Presign with the public Host from the outset: rewriting a signed URL breaks SigV4.
|
||||
client, err := minio.New(u.Host, &minio.Options{Creds: s.signingCreds, Secure: u.Scheme == "https", Region: s.region, BucketLookup: minio.BucketLookupPath})
|
||||
if err != nil {
|
||||
return "", unavailable("presign", err)
|
||||
}
|
||||
headers := http.Header{}
|
||||
headers.Set("Content-Type", contentType)
|
||||
headers.Set("Content-Length", fmt.Sprint(size))
|
||||
signed, err := client.PresignHeader(ctx, http.MethodPut, s.bucket, key, 60*time.Second, nil, headers)
|
||||
if err != nil {
|
||||
return "", unavailable("presign", err)
|
||||
}
|
||||
return signed.String(), nil
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
type Params struct {
|
||||
MemoryKiB uint32
|
||||
Iterations uint32
|
||||
Parallelism uint8
|
||||
SaltLen uint32
|
||||
KeyLen uint32
|
||||
}
|
||||
|
||||
var Default = Params{
|
||||
MemoryKiB: 19 * 1024,
|
||||
Iterations: 2,
|
||||
Parallelism: 1,
|
||||
SaltLen: 16,
|
||||
KeyLen: 32,
|
||||
}
|
||||
|
||||
var ErrMalformedHash = errors.New("password: malformed hash")
|
||||
|
||||
var b64 = base64.RawStdEncoding
|
||||
|
||||
type Hasher struct {
|
||||
params Params
|
||||
slots chan struct{}
|
||||
}
|
||||
|
||||
func NewHasher(p Params, maxConcurrent int) *Hasher {
|
||||
if maxConcurrent <= 0 {
|
||||
maxConcurrent = 1
|
||||
}
|
||||
return &Hasher{params: p, slots: make(chan struct{}, maxConcurrent)}
|
||||
}
|
||||
|
||||
func (h *Hasher) acquire(ctx context.Context) error {
|
||||
select {
|
||||
case h.slots <- struct{}{}:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hasher) release() { <-h.slots }
|
||||
|
||||
// Hash возвращает PHC-строку Argon2id со случайной солью.
|
||||
func (h *Hasher) Hash(ctx context.Context, plain string) (string, error) {
|
||||
salt := make([]byte, h.params.SaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("password: rand: %w", err)
|
||||
}
|
||||
if err := h.acquire(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer h.release()
|
||||
|
||||
p := h.params
|
||||
key := argon2.IDKey([]byte(plain), salt, p.Iterations, p.MemoryKiB, p.Parallelism, p.KeyLen)
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, p.MemoryKiB, p.Iterations, p.Parallelism,
|
||||
b64.EncodeToString(salt), b64.EncodeToString(key)), nil
|
||||
}
|
||||
|
||||
func (h *Hasher) Verify(ctx context.Context, plain, encoded string) (bool, error) {
|
||||
p, salt, want, err := decode(encoded)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := h.acquire(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer h.release()
|
||||
|
||||
got := argon2.IDKey([]byte(plain), salt, p.Iterations, p.MemoryKiB, p.Parallelism, uint32(len(want)))
|
||||
return subtle.ConstantTimeCompare(got, want) == 1, nil
|
||||
}
|
||||
|
||||
func decode(encoded string) (Params, []byte, []byte, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
var p Params
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.MemoryKiB, &p.Iterations, &p.Parallelism); err != nil {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
salt, err := b64.DecodeString(parts[4])
|
||||
if err != nil || len(salt) == 0 {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
key, err := b64.DecodeString(parts[5])
|
||||
if err != nil || len(key) == 0 {
|
||||
return Params{}, nil, nil, ErrMalformedHash
|
||||
}
|
||||
return p, salt, key, nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
const Pending = "attachments:pending"
|
||||
const Active = "attachments:active"
|
||||
|
||||
type Job struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
JobID string `json:"job_id"`
|
||||
Type string `json:"type"`
|
||||
AttachmentID string `json:"attachment_id"`
|
||||
PipelineVersion int `json:"pipeline_version"`
|
||||
Attempt int `json:"attempt"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func Client() *redis.Client {
|
||||
addr := os.Getenv("BROKER_ADDR")
|
||||
if addr == "" {
|
||||
addr = "broker:6379"
|
||||
}
|
||||
return redis.NewClient(&redis.Options{Addr: addr})
|
||||
}
|
||||
func Publish(ctx context.Context, id string, attempt int, created time.Time) error {
|
||||
c := Client()
|
||||
defer c.Close()
|
||||
b, err := json.Marshal(Job{1, id, "attachment.process.v1", id, 1, attempt, created.UTC()})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.LPush(ctx, Pending, string(b)).Err()
|
||||
}
|
||||
|
||||
// Dispatch republishes unfinished intentions. Duplicate messages are expected.
|
||||
func Dispatch(ctx context.Context, p *pgxpool.Pool) {
|
||||
for ctx.Err() == nil {
|
||||
func() {
|
||||
tx, err := p.Begin(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
rows, err := tx.Query(ctx, `SELECT o.attachment_id::text,a.attempts+1,a.created_at FROM attachment_outbox o JOIN attachments a ON a.id=o.attachment_id
|
||||
WHERE o.next_publish_at<=now() AND ((a.status='queued' AND a.next_attempt_at<=now()) OR (a.status='processing' AND a.lease_until<now()))
|
||||
ORDER BY o.next_publish_at LIMIT 16 FOR UPDATE OF o SKIP LOCKED`)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
type intent struct {
|
||||
id string
|
||||
attempt int
|
||||
created time.Time
|
||||
}
|
||||
var ids []intent
|
||||
for rows.Next() {
|
||||
var id intent
|
||||
if rows.Scan(&id.id, &id.attempt, &id.created) != nil {
|
||||
rows.Close()
|
||||
return
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
rows.Close()
|
||||
if rows.Err() != nil {
|
||||
return
|
||||
}
|
||||
for _, id := range ids {
|
||||
if Publish(ctx, id.id, id.attempt, id.created) != nil {
|
||||
return
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET next_publish_at=now()+interval '30 seconds' WHERE attachment_id=$1`, id.id); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
_ = tx.Commit(ctx)
|
||||
}()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/imagecheck"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var _ AttachmentsService = (*Attachments)(nil)
|
||||
|
||||
// ObjectKeyPrefix — префикс ключей оригиналов. Очиститель обходит только его.
|
||||
const ObjectKeyPrefix = "originals/"
|
||||
|
||||
// Предел на компенсирующее удаление объекта, когда запись метаданных не удалась.
|
||||
const compensationTimeout = 5 * time.Second
|
||||
|
||||
type AttachmentLimits struct {
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
MaxConcurrentUploads int
|
||||
}
|
||||
|
||||
type attachmentRepo interface {
|
||||
store.ChatStore
|
||||
store.AttachmentStore
|
||||
}
|
||||
|
||||
type Attachments struct {
|
||||
repo attachmentRepo
|
||||
objects objectstore.Store
|
||||
limits AttachmentLimits
|
||||
checker *imagecheck.Checker
|
||||
// uploads — слоты загрузок. Вместе с лимитом размера они ограничивают диск реплики под временные
|
||||
// файлы; память на одну загрузку от размера файла не зависит.
|
||||
uploads chan struct{}
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func NewAttachments(repo attachmentRepo, objects objectstore.Store, limits AttachmentLimits, logger *slog.Logger) *Attachments {
|
||||
return &Attachments{
|
||||
repo: repo,
|
||||
objects: objects,
|
||||
limits: limits,
|
||||
checker: imagecheck.New(limits.MaxImagePixels),
|
||||
uploads: make(chan struct{}, limits.MaxConcurrentUploads),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Upload сохраняет проверенный оригинал в staging и публикует устойчивое задание до ответа 202.
|
||||
func (a *Attachments) Upload(ctx context.Context, in UploadInput) (domain.Attachment, error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", in.ChatID)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if _, err := a.repo.ChatByID(ctx, in.CallerID, chatID); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := validate.Filename(in.Filename); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
declared, err := parseImageType(in.ContentType)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if in.ContentLength > a.limits.MaxUploadBytes {
|
||||
return domain.Attachment{}, domain.ErrPayloadTooLarge
|
||||
}
|
||||
|
||||
select {
|
||||
case a.uploads <- struct{}{}:
|
||||
defer func() { <-a.uploads }()
|
||||
default:
|
||||
return domain.Attachment{}, domain.ErrRateLimited
|
||||
}
|
||||
|
||||
spool, size, sum, err := a.spoolBody(in.Body)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
defer spool.Close()
|
||||
|
||||
if err := a.checkImage(ctx, spool, declared); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if _, err := spool.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
|
||||
id := uuid.NewString()
|
||||
att := domain.Attachment{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
OwnerID: in.CallerID,
|
||||
Filename: in.Filename,
|
||||
ContentType: declared,
|
||||
SizeBytes: size,
|
||||
SHA256: sum,
|
||||
ObjectKey: "staging/" + id,
|
||||
Status: "queued",
|
||||
}
|
||||
if err := a.objects.Put(ctx, att.ObjectKey, att.ContentType, spool, size); err != nil {
|
||||
// Объект мог успеть сохраниться. Удалять его здесь бессмысленно: при недоступном S3 удаление
|
||||
// тоже не пройдёт, а клиент лишние секунды ждал бы ответа. Его уберёт очиститель.
|
||||
a.logger.Warn("attachment object put failed", slog.Any("err", err))
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
saved, err := a.repo.CreateAttachment(ctx, att)
|
||||
if err != nil {
|
||||
a.compensate(ctx, att)
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if os.Getenv("FAULT_AFTER_UPLOAD_COMMIT") == "1" {
|
||||
os.Exit(86)
|
||||
} // Только для локальной проверки окна COMMIT/publish.
|
||||
return saved, nil
|
||||
}
|
||||
|
||||
// checkImage сравнивает заявленный тип с настоящим до декодирования: подмена типа не тратит память.
|
||||
func (a *Attachments) checkImage(ctx context.Context, file io.ReadSeeker, declared string) error {
|
||||
detected, err := a.checker.Inspect(file)
|
||||
if err == nil && detected != declared {
|
||||
return domain.ErrUnsupportedMedia
|
||||
}
|
||||
if err == nil {
|
||||
err = a.checker.Decode(ctx, file)
|
||||
}
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case errors.Is(err, imagecheck.ErrTooManyPixels):
|
||||
return domain.ErrPayloadTooLarge
|
||||
case errors.Is(err, imagecheck.ErrUnsupported):
|
||||
return domain.ErrUnsupportedMedia
|
||||
case errors.Is(err, imagecheck.ErrBusy):
|
||||
return domain.ErrRateLimited
|
||||
}
|
||||
return fmt.Errorf("%w: image check: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
|
||||
// compensate убирает объект, для которого метаданные не сохранились. Контекст отвязан от запроса:
|
||||
// клиент мог уже отключиться. Удалять можно, только убедившись, что строки нет: ошибка INSERT не
|
||||
// доказывает отсутствие записи (COMMIT мог пройти, а ответ потеряться), и удаление оставило бы
|
||||
// подтверждённую строку без файла. Если проверить нельзя, объект остаётся очистителю: он удаляет
|
||||
// только объекты без строки и только после grace period (cmd/janitor).
|
||||
func (a *Attachments) compensate(ctx context.Context, att domain.Attachment) {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), compensationTimeout)
|
||||
defer cancel()
|
||||
exists, err := a.repo.AttachmentExists(ctx, att.ID)
|
||||
if err != nil {
|
||||
a.logger.Warn("orphan check failed, object is left to the janitor", slog.String("object_key", att.ObjectKey), slog.Any("err", err))
|
||||
return
|
||||
}
|
||||
if exists {
|
||||
a.logger.Warn("metadata write reported an error but the row exists, object is kept", slog.String("attachment_id", att.ID))
|
||||
return
|
||||
}
|
||||
if err := a.objects.Delete(ctx, att.ObjectKey); err != nil {
|
||||
a.logger.Warn("compensating delete failed, object is left to the janitor", slog.String("object_key", att.ObjectKey), slog.Any("err", err))
|
||||
}
|
||||
}
|
||||
|
||||
// spoolBody пишет тело во временный файл и считает SHA-256 на лету. Файл удаляется из каталога сразу
|
||||
// после создания: данные живут, пока он открыт, поэтому при любом завершении, даже kill -9, на диске
|
||||
// ничего не остаётся и отдельная уборка не нужна. Это не хранилище: 201 вернётся только после S3.
|
||||
func (a *Attachments) spoolBody(body io.Reader) (*os.File, int64, string, error) {
|
||||
file, err := os.CreateTemp("", "upload-*")
|
||||
if err != nil {
|
||||
return nil, 0, "", fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
if err := os.Remove(file.Name()); err != nil {
|
||||
file.Close()
|
||||
return nil, 0, "", fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
|
||||
hash := sha256.New()
|
||||
source := &errorTrackingReader{r: body}
|
||||
// LimitReader на байт больше лимита: так отличается файл ровно на границе от файла больше неё.
|
||||
n, err := io.Copy(io.MultiWriter(file, hash), io.LimitReader(source, a.limits.MaxUploadBytes+1))
|
||||
switch {
|
||||
case source.err != nil:
|
||||
file.Close()
|
||||
// Клиент оборвал передачу или не уложился в таймаут. Отвечать чаще всего уже некому.
|
||||
return nil, 0, "", &validate.Error{Field: "body", Reason: "cannot read body"}
|
||||
case err != nil:
|
||||
file.Close()
|
||||
return nil, 0, "", fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err)
|
||||
case n > a.limits.MaxUploadBytes:
|
||||
file.Close()
|
||||
return nil, 0, "", domain.ErrPayloadTooLarge
|
||||
}
|
||||
return file, n, hex.EncodeToString(hash.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// errorTrackingReader отделяет ошибку чтения от клиента (400) от ошибки записи на диск (503).
|
||||
type errorTrackingReader struct {
|
||||
r io.Reader
|
||||
err error
|
||||
}
|
||||
|
||||
func (e *errorTrackingReader) Read(p []byte) (int, error) {
|
||||
n, err := e.r.Read(p)
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
e.err = err
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func parseImageType(header string) (string, error) {
|
||||
mediaType, _, err := mime.ParseMediaType(header)
|
||||
if err != nil {
|
||||
return "", domain.ErrUnsupportedMedia
|
||||
}
|
||||
switch mediaType {
|
||||
case domain.ContentTypePNG, domain.ContentTypeJPEG:
|
||||
return mediaType, nil
|
||||
}
|
||||
return "", domain.ErrUnsupportedMedia
|
||||
}
|
||||
|
||||
func (a *Attachments) Get(ctx context.Context, callerID, attachmentID string) (domain.Attachment, error) {
|
||||
id, err := validate.CanonicalUUID("attachment_id", attachmentID)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return a.repo.AttachmentForMember(ctx, callerID, id)
|
||||
}
|
||||
|
||||
func (a *Attachments) Content(ctx context.Context, callerID, attachmentID, variant string) (domain.Attachment, io.ReadCloser, error) {
|
||||
if err := validateVariantName(variant); err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
att, err := a.Get(ctx, callerID, attachmentID)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
if att.Status != domain.StatusReady {
|
||||
return domain.Attachment{}, nil, domain.ErrConflict
|
||||
}
|
||||
if variant != VariantOriginal {
|
||||
found := false
|
||||
for _, v := range att.Variants {
|
||||
if v.Name == variant {
|
||||
att.ObjectKey = variant + "s/" + att.ID
|
||||
att.ContentType, att.SizeBytes, att.SHA256 = v.ContentType, v.SizeBytes, v.SHA256
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return domain.Attachment{}, nil, domain.ErrNotFound
|
||||
}
|
||||
}
|
||||
body, size, err := a.objects.Get(ctx, att.ObjectKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, objectstore.ErrNotFound) {
|
||||
return domain.Attachment{}, nil, fmt.Errorf("attachment %s: object missing in bucket", att.ID)
|
||||
}
|
||||
a.logger.Warn("attachment object get failed", slog.Any("err", err))
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
if size != att.SizeBytes {
|
||||
body.Close()
|
||||
return domain.Attachment{}, nil, fmt.Errorf("attachment %s: object size %d differs from metadata %d", att.ID, size, att.SizeBytes)
|
||||
}
|
||||
return att, body, nil
|
||||
}
|
||||
|
||||
func validateVariantName(variant string) error {
|
||||
switch variant {
|
||||
case VariantOriginal, "thumbnail", "crop", "optimized":
|
||||
return nil
|
||||
}
|
||||
return &validate.Error{Field: "variant", Reason: "unknown variant"}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/token"
|
||||
)
|
||||
|
||||
var (
|
||||
_ AuthService = (*Auth)(nil)
|
||||
)
|
||||
|
||||
type Auth struct {
|
||||
users store.UserStore
|
||||
sessions session.Store
|
||||
hasher *password.Hasher
|
||||
ttl time.Duration
|
||||
now func() time.Time
|
||||
|
||||
dummyHash string
|
||||
}
|
||||
|
||||
func NewAuth(users store.UserStore, sessions session.Store, hasher *password.Hasher, ttl time.Duration) (*Auth, error) {
|
||||
dummy, err := hasher.Hash(context.Background(), "dummy-password-for-timing")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("auth: dummy hash: %w", err)
|
||||
}
|
||||
return &Auth{
|
||||
users: users,
|
||||
sessions: sessions,
|
||||
hasher: hasher,
|
||||
ttl: ttl,
|
||||
now: time.Now,
|
||||
dummyHash: dummy,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *Auth) Login(ctx context.Context, username, plainPassword string) (domain.Session, error) {
|
||||
user, hash, err := a.users.CredentialsByUsername(ctx, username)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
_, _ = a.hasher.Verify(ctx, plainPassword, a.dummyHash)
|
||||
return domain.Session{}, domain.ErrUnauthorized
|
||||
case err != nil:
|
||||
return domain.Session{}, err
|
||||
}
|
||||
|
||||
ok, err := a.hasher.Verify(ctx, plainPassword, hash)
|
||||
if err != nil {
|
||||
if errors.Is(err, password.ErrMalformedHash) {
|
||||
return domain.Session{}, domain.ErrUnauthorized
|
||||
}
|
||||
return domain.Session{}, err
|
||||
}
|
||||
if !ok {
|
||||
return domain.Session{}, domain.ErrUnauthorized
|
||||
}
|
||||
|
||||
plain, tokenHash, err := token.New()
|
||||
if err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
expiresAt := a.now().Add(a.ttl).UTC().Truncate(time.Second)
|
||||
if err := a.sessions.Save(ctx, tokenHash, session.Session{UserID: user.ID, ExpiresAt: expiresAt}); err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
return domain.Session{Token: plain, ExpiresAt: expiresAt, User: user}, nil
|
||||
}
|
||||
|
||||
func (a *Auth) Authenticate(ctx context.Context, plainToken string) (string, error) {
|
||||
tokenHash, err := token.Parse(plainToken)
|
||||
if err != nil {
|
||||
return "", domain.ErrUnauthorized
|
||||
}
|
||||
s, err := a.sessions.Get(ctx, tokenHash)
|
||||
if errors.Is(err, session.ErrNotFound) {
|
||||
return "", domain.ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !a.now().Before(s.ExpiresAt) {
|
||||
return "", domain.ErrUnauthorized
|
||||
}
|
||||
return s.UserID, nil
|
||||
}
|
||||
|
||||
func (a *Auth) Logout(ctx context.Context, plainToken string) error {
|
||||
tokenHash, err := token.Parse(plainToken)
|
||||
if err != nil {
|
||||
return domain.ErrUnauthorized
|
||||
}
|
||||
return a.sessions.Delete(ctx, tokenHash)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var (
|
||||
_ ChatsService = (*Chats)(nil)
|
||||
)
|
||||
|
||||
type Chats struct {
|
||||
store store.ChatStore
|
||||
}
|
||||
|
||||
func NewChats(s store.ChatStore) *Chats {
|
||||
return &Chats{store: s}
|
||||
}
|
||||
|
||||
func (c *Chats) Create(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) {
|
||||
if err := validate.ChatTitle(title); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
memberIDs, err := validate.MemberIDs(memberIDs, callerID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
return c.store.CreateChat(ctx, callerID, title, memberIDs)
|
||||
}
|
||||
|
||||
func (c *Chats) Get(ctx context.Context, callerID, chatID string) (domain.Chat, error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", chatID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
return c.store.ChatByID(ctx, callerID, chatID)
|
||||
}
|
||||
|
||||
func (c *Chats) List(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) {
|
||||
if err := validate.Limit(limit); err != nil {
|
||||
return domain.Page[domain.Chat]{}, err
|
||||
}
|
||||
return c.store.ListChats(ctx, callerID, cursor, limit)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var (
|
||||
_ MessagesService = (*Messages)(nil)
|
||||
)
|
||||
|
||||
type Messages struct {
|
||||
store store.MessageStore
|
||||
}
|
||||
|
||||
func NewMessages(s store.MessageStore) *Messages {
|
||||
return &Messages{store: s}
|
||||
}
|
||||
|
||||
func (m *Messages) Send(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", chatID)
|
||||
if err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if err := validate.IdempotencyKey(idempotencyKey); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
ids, err := validate.AttachmentIDs(attachmentIDs)
|
||||
if err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if err := validate.MessageText(text, len(ids) > 0); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
return m.store.AddMessage(ctx, callerID, chatID, idempotencyKey, text, ids)
|
||||
}
|
||||
|
||||
func (m *Messages) List(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", chatID)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
if err := validate.Limit(limit); err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
return m.store.ListMessages(ctx, callerID, chatID, cursor, limit)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
type UsersService interface {
|
||||
Register(ctx context.Context, username, displayName, password string) (domain.User, error)
|
||||
Me(ctx context.Context, callerID string) (domain.User, error)
|
||||
}
|
||||
|
||||
type ChatsService interface {
|
||||
Create(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error)
|
||||
Get(ctx context.Context, callerID, chatID string) (domain.Chat, error)
|
||||
List(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error)
|
||||
}
|
||||
|
||||
type MessagesService interface {
|
||||
Send(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error)
|
||||
List(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error)
|
||||
}
|
||||
|
||||
// VariantOriginal — вариант содержимого по умолчанию.
|
||||
const VariantOriginal = "original"
|
||||
|
||||
// UploadInput — параметры загрузки файла. Body читается не дальше лимита размера.
|
||||
type UploadInput struct {
|
||||
CallerID string
|
||||
ChatID string
|
||||
Filename string
|
||||
ContentType string
|
||||
ContentLength int64
|
||||
Body io.Reader
|
||||
}
|
||||
|
||||
type AttachmentsService interface {
|
||||
Upload(ctx context.Context, in UploadInput) (domain.Attachment, error)
|
||||
Get(ctx context.Context, callerID, attachmentID string) (domain.Attachment, error)
|
||||
// Content возвращает метаданные и поток байтов. Поток обязательно закрыть.
|
||||
Content(ctx context.Context, callerID, attachmentID, variant string) (domain.Attachment, io.ReadCloser, error)
|
||||
}
|
||||
|
||||
type AuthService interface {
|
||||
Login(ctx context.Context, username, password string) (domain.Session, error)
|
||||
Authenticate(ctx context.Context, token string) (userID string, err error)
|
||||
Logout(ctx context.Context, token string) error
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var (
|
||||
_ UsersService = (*Users)(nil)
|
||||
)
|
||||
|
||||
type Users struct {
|
||||
store store.UserStore
|
||||
hasher *password.Hasher
|
||||
}
|
||||
|
||||
func NewUsers(s store.UserStore, h *password.Hasher) *Users {
|
||||
return &Users{store: s, hasher: h}
|
||||
}
|
||||
|
||||
func (u *Users) Register(ctx context.Context, username, displayName, plainPassword string) (domain.User, error) {
|
||||
if err := validate.Username(username); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if err := validate.DisplayName(displayName); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if err := validate.Password(plainPassword); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
hash, err := u.hasher.Hash(ctx, plainPassword)
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
return u.store.CreateUser(ctx, username, displayName, hash)
|
||||
}
|
||||
|
||||
func (u *Users) Me(ctx context.Context, callerID string) (domain.User, error) {
|
||||
return u.store.UserByID(ctx, callerID)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var _ Store = (*Memory)(nil)
|
||||
|
||||
type Memory struct {
|
||||
mu sync.Mutex
|
||||
sessions map[string]Session
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewMemory() *Memory {
|
||||
return &Memory{sessions: make(map[string]Session), now: time.Now}
|
||||
}
|
||||
|
||||
func (m *Memory) Save(_ context.Context, tokenHash []byte, s Session) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.sessions[string(tokenHash)] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Get(_ context.Context, tokenHash []byte) (Session, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
s, ok := m.sessions[string(tokenHash)]
|
||||
if !ok {
|
||||
return Session{}, ErrNotFound
|
||||
}
|
||||
if !m.now().Before(s.ExpiresAt) {
|
||||
delete(m.sessions, string(tokenHash))
|
||||
return Session{}, ErrNotFound
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (m *Memory) Delete(_ context.Context, tokenHash []byte) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.sessions, string(tokenHash))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Ping(context.Context) error { return nil }
|
||||
@@ -0,0 +1,21 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
UserID string `json:"user_id"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
var ErrNotFound = errors.New("session: not found")
|
||||
|
||||
type Store interface {
|
||||
Save(ctx context.Context, tokenHash []byte, s Session) error
|
||||
Get(ctx context.Context, tokenHash []byte) (Session, error)
|
||||
Delete(ctx context.Context, tokenHash []byte) error
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
var _ Store = (*Valkey)(nil)
|
||||
|
||||
const keyPrefix = "session:"
|
||||
|
||||
type Valkey struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewValkey(client *redis.Client) *Valkey {
|
||||
return &Valkey{client: client}
|
||||
}
|
||||
|
||||
func Connect(ctx context.Context, cfg config.Cache) (*redis.Client, error) {
|
||||
url, err := urlFrom(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opts, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, errors.New("session: invalid CACHE_URL")
|
||||
}
|
||||
timeout := time.Duration(cfg.TimeoutMs) * time.Millisecond
|
||||
opts.PoolSize = cfg.PoolSize
|
||||
opts.DialTimeout = timeout
|
||||
opts.ReadTimeout = timeout
|
||||
opts.WriteTimeout = timeout
|
||||
opts.PoolTimeout = timeout
|
||||
opts.MaxRetries = 1
|
||||
|
||||
client := redis.NewClient(opts)
|
||||
pingCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
if err := client.Ping(pingCtx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
return nil, fmt.Errorf("session: ping: %w", err)
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func urlFrom(cfg config.Cache) (string, error) {
|
||||
if cfg.URLFile != "" {
|
||||
b, err := os.ReadFile(cfg.URLFile)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("session: read CACHE_URL_FILE: %w", err)
|
||||
}
|
||||
return strings.TrimSpace(string(b)), nil
|
||||
}
|
||||
if cfg.URL != "" {
|
||||
return cfg.URL, nil
|
||||
}
|
||||
return "", errors.New("session: CACHE_URL_FILE or CACHE_URL is required")
|
||||
}
|
||||
|
||||
func key(tokenHash []byte) string {
|
||||
return keyPrefix + hex.EncodeToString(tokenHash)
|
||||
}
|
||||
|
||||
func (v *Valkey) Save(ctx context.Context, tokenHash []byte, s Session) error {
|
||||
val, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// NX: 256-битный токен не совпадёт, но перезаписать чужую сессию нельзя даже теоретически.
|
||||
err = v.client.SetArgs(ctx, key(tokenHash), val, redis.SetArgs{
|
||||
Mode: "NX",
|
||||
ExpireAt: s.ExpiresAt,
|
||||
}).Err()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return fmt.Errorf("session: token collision")
|
||||
}
|
||||
return unavailable(err)
|
||||
}
|
||||
|
||||
func (v *Valkey) Get(ctx context.Context, tokenHash []byte) (Session, error) {
|
||||
val, err := v.client.Get(ctx, key(tokenHash)).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return Session{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return Session{}, unavailable(err)
|
||||
}
|
||||
var s Session
|
||||
if err := json.Unmarshal(val, &s); err != nil {
|
||||
return Session{}, fmt.Errorf("session: corrupt value: %w", err)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (v *Valkey) Delete(ctx context.Context, tokenHash []byte) error {
|
||||
return unavailable(v.client.Del(ctx, key(tokenHash)).Err())
|
||||
}
|
||||
|
||||
func (v *Valkey) Ping(ctx context.Context) error {
|
||||
return unavailable(v.client.Ping(ctx).Err())
|
||||
}
|
||||
|
||||
func unavailable(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%w: session store: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
type Attachments struct {
|
||||
conn
|
||||
}
|
||||
|
||||
// CreateAttachment сохраняет метаданные. FK на chat_members не даёт записать вложение постороннего.
|
||||
func (a *Attachments) CreateAttachment(ctx context.Context, att domain.Attachment) (domain.Attachment, error) {
|
||||
ctx, cancel := a.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := a.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
// Serialize admission across API replicas. Only unfinished jobs consume capacity.
|
||||
limit := 64
|
||||
if value := os.Getenv("JOB_MAX_INFLIGHT"); value != "" {
|
||||
n, e := strconv.Atoi(value)
|
||||
if e != nil || n < 1 {
|
||||
return domain.Attachment{}, fmt.Errorf("invalid JOB_MAX_INFLIGHT")
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(505002)`); err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
var outstanding int
|
||||
if err = tx.QueryRow(ctx, `SELECT count(*) FROM attachments WHERE status IN ('queued','processing')`).Scan(&outstanding); err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
if outstanding >= limit {
|
||||
return domain.Attachment{}, domain.ErrRateLimited
|
||||
}
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
RETURNING created_at, updated_at`,
|
||||
att.ID, att.ChatID, att.OwnerID, att.Filename, att.ContentType, att.SizeBytes, att.SHA256, att.ObjectKey, att.Status,
|
||||
).Scan(&att.CreatedAt, &att.UpdatedAt)
|
||||
if isFKViolation(err) {
|
||||
return domain.Attachment{}, domain.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(attachment_id) VALUES ($1)`, att.ID); err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
att.CreatedAt = att.CreatedAt.UTC()
|
||||
att.UpdatedAt = att.UpdatedAt.UTC()
|
||||
return att, nil
|
||||
}
|
||||
|
||||
// AttachmentForMember возвращает вложение, только если вызывающий состоит в его чате: для
|
||||
// постороннего результат неотличим от отсутствующего объекта.
|
||||
func (a *Attachments) AttachmentForMember(ctx context.Context, callerID, attachmentID string) (domain.Attachment, error) {
|
||||
ctx, cancel := a.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var att domain.Attachment
|
||||
err := a.pool.QueryRow(ctx, `
|
||||
SELECT a.id::text, a.chat_id::text, a.owner_id::text, a.filename, a.content_type, a.size_bytes,
|
||||
a.sha256, a.object_key, a.status, a.created_at, a.updated_at, a.thumbnail, a.error_code, a.variants
|
||||
FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2
|
||||
WHERE a.id = $1`,
|
||||
attachmentID, callerID,
|
||||
).Scan(&att.ID, &att.ChatID, &att.OwnerID, &att.Filename, &att.ContentType, &att.SizeBytes,
|
||||
&att.SHA256, &att.ObjectKey, &att.Status, &att.CreatedAt, &att.UpdatedAt, &att.Thumbnail, &att.ErrorCode, &att.Variants)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, mapErr(err)
|
||||
}
|
||||
att.CreatedAt = att.CreatedAt.UTC()
|
||||
att.UpdatedAt = att.UpdatedAt.UTC()
|
||||
return att, nil
|
||||
}
|
||||
|
||||
// AttachmentExists отвечает без учёта доступа: вызывается только сервером при компенсации.
|
||||
func (a *Attachments) AttachmentExists(ctx context.Context, attachmentID string) (bool, error) {
|
||||
ctx, cancel := a.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var exists bool
|
||||
err := a.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM attachments WHERE id = $1)`, attachmentID).Scan(&exists)
|
||||
if err != nil {
|
||||
return false, mapErr(err)
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
// ExistingObjectKeys возвращает те ключи из списка, на которые есть строка. Нужен очистителю.
|
||||
func (a *Attachments) ExistingObjectKeys(ctx context.Context, keys []string) (map[string]struct{}, error) {
|
||||
ctx, cancel := a.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := a.pool.Query(ctx, `SELECT object_key FROM attachments WHERE object_key = ANY($1)`, keys)
|
||||
if err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
existing := make(map[string]struct{}, len(keys))
|
||||
for rows.Next() {
|
||||
var key string
|
||||
if err := rows.Scan(&key); err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
existing[key] = struct{}{}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
return existing, nil
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
type Chats struct {
|
||||
conn
|
||||
}
|
||||
|
||||
func (c *Chats) CreateChat(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) {
|
||||
if strings.TrimSpace(title) == "" {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
if len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
callerInMembers := false
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if id == callerID {
|
||||
callerInMembers = true
|
||||
}
|
||||
}
|
||||
if !callerInMembers {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
ctx, cancel := c.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := c.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return domain.Chat{}, mapErr(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
chat := domain.Chat{Title: title}
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO chats (title)
|
||||
VALUES ($1)
|
||||
RETURNING id::text, created_at`,
|
||||
encodeText(title),
|
||||
).Scan(&chat.ID, &chat.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Chat{}, mapErr(err)
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT $1, unnest($2::uuid[])`,
|
||||
chat.ID, memberIDs,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Chat{}, mapErr(err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return domain.Chat{}, mapErr(err)
|
||||
}
|
||||
|
||||
chat.MemberIDs = append([]string(nil), memberIDs...)
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (c *Chats) ChatByID(ctx context.Context, callerID, chatID string) (domain.Chat, error) {
|
||||
ctx, cancel := c.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
chat := domain.Chat{}
|
||||
err := c.pool.QueryRow(ctx, `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
(SELECT array_agg(m.user_id::text ORDER BY m.user_id)
|
||||
FROM chat_members m WHERE m.chat_id = c.id)
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2
|
||||
WHERE c.id = $1`,
|
||||
chatID, callerID,
|
||||
).Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
|
||||
if err != nil {
|
||||
err = mapErr(err)
|
||||
if err == domain.ErrInvalidArgument {
|
||||
return domain.Chat{}, domain.ErrNotFound
|
||||
}
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
chat.Title = decodeText(chat.Title)
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (c *Chats) ListChats(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) {
|
||||
if limit <= 0 || limit > 100 {
|
||||
return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
cur, err := domain.DecodeCursor(cursor)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, err
|
||||
}
|
||||
scope := "chats:" + callerID
|
||||
if cursor != "" && cur.Scope != scope {
|
||||
return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
afterTime, afterID := cursorArgs(cur)
|
||||
|
||||
ctx, cancel := c.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := c.pool.Query(ctx, `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
(SELECT array_agg(m.user_id::text ORDER BY m.user_id)
|
||||
FROM chat_members m WHERE m.chat_id = c.id)
|
||||
FROM chat_members me
|
||||
JOIN chats c ON c.id = me.chat_id
|
||||
WHERE me.user_id = $1
|
||||
AND ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid))
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`,
|
||||
callerID, afterTime, afterID, limit+1,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, mapErr(err)
|
||||
}
|
||||
out, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (domain.Chat, error) {
|
||||
var ch domain.Chat
|
||||
err := r.Scan(&ch.ID, &ch.Title, &ch.CreatedAt, &ch.MemberIDs)
|
||||
ch.Title = decodeText(ch.Title)
|
||||
ch.CreatedAt = ch.CreatedAt.UTC()
|
||||
return ch, err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, mapErr(err)
|
||||
}
|
||||
|
||||
page := domain.Page[domain.Chat]{}
|
||||
if len(out) > limit {
|
||||
last := out[limit-1]
|
||||
page.NextCursor = domain.EncodeCursor(domain.Cursor{
|
||||
CreatedAt: last.CreatedAt,
|
||||
ID: last.ID,
|
||||
Scope: scope,
|
||||
})
|
||||
out = out[:limit]
|
||||
}
|
||||
page.Items = out
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func cursorArgs(c domain.Cursor) (*time.Time, *string) {
|
||||
if c.IsZero() {
|
||||
return nil, nil
|
||||
}
|
||||
return &c.CreatedAt, &c.ID
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
)
|
||||
|
||||
var _ store.Store = (*DB)(nil)
|
||||
|
||||
type DB struct {
|
||||
*Users
|
||||
*Chats
|
||||
*Messages
|
||||
*Attachments
|
||||
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, queryTimeout time.Duration) *DB {
|
||||
c := conn{pool: pool, timeout: queryTimeout}
|
||||
return &DB{
|
||||
Users: &Users{conn: c},
|
||||
Chats: &Chats{conn: c},
|
||||
Messages: &Messages{conn: c},
|
||||
Attachments: &Attachments{conn: c},
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func Connect(ctx context.Context, cfg config.Database) (*pgxpool.Pool, error) {
|
||||
dsn, err := dsnFrom(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pcfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, errors.New("db: invalid DSN")
|
||||
}
|
||||
pcfg.MaxConns = cfg.MaxConns
|
||||
pcfg.ConnConfig.ConnectTimeout = time.Duration(cfg.ConnectTimeoutMs) * time.Millisecond
|
||||
if !cfg.EnableBitmapScan {
|
||||
pcfg.ConnConfig.RuntimeParams["enable_bitmapscan"] = "off"
|
||||
}
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, pcfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("db: pool: %w", err)
|
||||
}
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, pcfg.ConnConfig.ConnectTimeout)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("db: ping: %w", err)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
func dsnFrom(cfg config.Database) (string, error) {
|
||||
if cfg.URLFile != "" {
|
||||
b, err := os.ReadFile(cfg.URLFile)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("db: read DATABASE_URL_FILE: %w", err)
|
||||
}
|
||||
return strings.TrimSpace(string(b)), nil
|
||||
}
|
||||
if cfg.URL != "" {
|
||||
return cfg.URL, nil
|
||||
}
|
||||
return "", errors.New("db: DATABASE_URL_FILE or DATABASE_URL is required")
|
||||
}
|
||||
|
||||
func (d *DB) Ping(ctx context.Context) error {
|
||||
return d.pool.Ping(ctx)
|
||||
}
|
||||
|
||||
func (d *DB) Close() {
|
||||
d.pool.Close()
|
||||
}
|
||||
|
||||
type conn struct {
|
||||
pool *pgxpool.Pool
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func (c conn) withTimeout(parent context.Context) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(parent, c.timeout)
|
||||
}
|
||||
|
||||
const (
|
||||
codeUniqueViolation = "23505"
|
||||
codeForeignKeyViolation = "23503"
|
||||
codeCheckViolation = "23514"
|
||||
codeInvalidTextRepr = "22P02"
|
||||
)
|
||||
|
||||
func mapErr(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.ErrNotFound
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case codeUniqueViolation:
|
||||
return domain.ErrConflict
|
||||
case codeForeignKeyViolation, codeCheckViolation, codeInvalidTextRepr:
|
||||
return domain.ErrInvalidArgument
|
||||
}
|
||||
switch pgErr.Code[:2] {
|
||||
case "08", "53", "57":
|
||||
return fmt.Errorf("%w: db: %s", domain.ErrUnavailable, pgErr.Code)
|
||||
}
|
||||
return fmt.Errorf("db: %s: %w", pgErr.Code, err)
|
||||
}
|
||||
return fmt.Errorf("%w: db: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
|
||||
func isFKViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == codeForeignKeyViolation
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (m *Messages) AddPendingInvalidation(ctx context.Context, chatID string) (int64, error) {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var gen int64
|
||||
err := m.pool.QueryRow(ctx, `
|
||||
INSERT INTO cache_invalidations (chat_id) VALUES ($1)
|
||||
ON CONFLICT (chat_id) DO UPDATE
|
||||
SET gen = nextval('cache_invalidations_gen_seq'), updated_at = now()
|
||||
RETURNING gen`,
|
||||
chatID,
|
||||
).Scan(&gen)
|
||||
if err != nil {
|
||||
return 0, mapErr(err)
|
||||
}
|
||||
return gen, nil
|
||||
}
|
||||
|
||||
func (m *Messages) PendingInvalidations(ctx context.Context) (map[string]int64, error) {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := m.pool.Query(ctx, `SELECT chat_id::text, gen FROM cache_invalidations`)
|
||||
if err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
out := map[string]int64{}
|
||||
var (
|
||||
id string
|
||||
gen int64
|
||||
)
|
||||
_, err = pgx.ForEachRow(rows, []any{&id, &gen}, func() error {
|
||||
out[id] = gen
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, mapErr(err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *Messages) ResolvePendingInvalidation(ctx context.Context, chatID string, gen int64) error {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := m.pool.Exec(ctx,
|
||||
`DELETE FROM cache_invalidations WHERE chat_id = $1 AND gen = $2`,
|
||||
chatID, gen,
|
||||
)
|
||||
return mapErr(err)
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
type Messages struct {
|
||||
conn
|
||||
}
|
||||
|
||||
func (m *Messages) AddMessage(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) {
|
||||
if strings.TrimSpace(text) == "" && len(attachmentIDs) == 0 {
|
||||
return domain.Message{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := m.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
msg := domain.Message{ChatID: chatID, AuthorID: callerID, Text: text, AttachmentIDs: attachmentIDs}
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO message_idempotency_keys (user_id, chat_id, key, message_id)
|
||||
VALUES ($1, $2, $3, gen_random_uuid())
|
||||
ON CONFLICT (user_id, chat_id, key) DO NOTHING
|
||||
RETURNING message_id::text`,
|
||||
callerID, chatID, idempotencyKey,
|
||||
).Scan(&msg.ID)
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
return replayMessage(ctx, tx, callerID, chatID, idempotencyKey, text, attachmentIDs)
|
||||
case isFKViolation(err):
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
case err != nil:
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING created_at`,
|
||||
msg.ID, chatID, callerID, encodeText(text),
|
||||
).Scan(&msg.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
// Составной FK сам отклоняет вложение другого чата и неизвестное вложение. Та же транзакция:
|
||||
// при ошибке не останется ни сообщения, ни ключа идемпотентности.
|
||||
if len(attachmentIDs) > 0 {
|
||||
rows, e := tx.Query(ctx, `SELECT id::text, status FROM attachments WHERE chat_id=$1 AND id=ANY($2::uuid[]) FOR SHARE`, chatID, attachmentIDs)
|
||||
if e != nil {
|
||||
return domain.Message{}, mapErr(e)
|
||||
}
|
||||
count := 0
|
||||
failed := false
|
||||
for rows.Next() {
|
||||
var id, status string
|
||||
if e = rows.Scan(&id, &status); e != nil {
|
||||
rows.Close()
|
||||
return domain.Message{}, mapErr(e)
|
||||
}
|
||||
count++
|
||||
failed = failed || status == "failed"
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return domain.Message{}, mapErr(e)
|
||||
}
|
||||
if count != len(attachmentIDs) {
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
}
|
||||
if failed {
|
||||
return domain.Message{}, domain.ErrConflict
|
||||
}
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO message_attachments (message_id, chat_id, attachment_id, position)
|
||||
SELECT $1, $2, t.id::uuid, t.ord::int
|
||||
FROM unnest($3::text[]) WITH ORDINALITY AS t(id, ord)`,
|
||||
msg.ID, chatID, attachmentIDs,
|
||||
)
|
||||
if isFKViolation(err) {
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func replayMessage(ctx context.Context, tx pgx.Tx, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) {
|
||||
msg := domain.Message{ChatID: chatID, AuthorID: callerID}
|
||||
err := tx.QueryRow(ctx, `
|
||||
SELECT m.id::text, m.text, m.created_at, COALESCE((SELECT array_agg(ma.attachment_id::text ORDER BY ma.position) FROM message_attachments ma WHERE ma.message_id = m.id), ARRAY[]::text[])
|
||||
FROM message_idempotency_keys k
|
||||
JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3`,
|
||||
callerID, chatID, idempotencyKey,
|
||||
).Scan(&msg.ID, &msg.Text, &msg.CreatedAt, &msg.AttachmentIDs)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Message{}, domain.ErrUnavailable
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Message{}, mapErr(err)
|
||||
}
|
||||
msg.Text = decodeText(msg.Text)
|
||||
if msg.Text != text || !slices.Equal(msg.AttachmentIDs, attachmentIDs) {
|
||||
return domain.Message{}, domain.ErrIdempotencyConflict
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func (m *Messages) PurgeIdempotencyKeys(ctx context.Context, ttl time.Duration) (int64, error) {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tag, err := m.pool.Exec(ctx,
|
||||
`DELETE FROM message_idempotency_keys WHERE created_at < now() - make_interval(secs => $1)`,
|
||||
ttl.Seconds(),
|
||||
)
|
||||
if err != nil {
|
||||
return 0, mapErr(err)
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
func (m *Messages) ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
member, err := m.IsMember(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
if !member {
|
||||
return domain.Page[domain.Message]{}, domain.ErrNotFound
|
||||
}
|
||||
return m.HistoryPage(ctx, chatID, cursor, limit)
|
||||
}
|
||||
|
||||
func (m *Messages) IsMember(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var member bool
|
||||
err := m.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, userID,
|
||||
).Scan(&member)
|
||||
if err != nil {
|
||||
return false, mapErr(err)
|
||||
}
|
||||
return member, nil
|
||||
}
|
||||
|
||||
func (m *Messages) HistoryPage(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
if limit <= 0 || limit > 100 {
|
||||
return domain.Page[domain.Message]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
cur, err := domain.DecodeCursor(cursor)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
scope := "chat:" + chatID
|
||||
if cursor != "" && cur.Scope != scope {
|
||||
return domain.Page[domain.Message]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
ctx, cancel := m.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var rows pgx.Rows
|
||||
if cur.IsZero() {
|
||||
rows, err = m.pool.Query(ctx, `
|
||||
SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at,
|
||||
COALESCE((SELECT array_agg(ma.attachment_id::text ORDER BY ma.position) FROM message_attachments ma WHERE ma.message_id = m.id), ARRAY[]::text[])
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $2`,
|
||||
chatID, limit+1,
|
||||
)
|
||||
} else {
|
||||
rows, err = m.pool.Query(ctx, `
|
||||
SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at,
|
||||
COALESCE((SELECT array_agg(ma.attachment_id::text ORDER BY ma.position) FROM message_attachments ma WHERE ma.message_id = m.id), ARRAY[]::text[])
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
AND (m.created_at, m.id) > ($2, $3::uuid)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4`,
|
||||
chatID, cur.CreatedAt, cur.ID, limit+1,
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, mapErr(err)
|
||||
}
|
||||
out, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (domain.Message, error) {
|
||||
var msg domain.Message
|
||||
err := r.Scan(&msg.ID, &msg.ChatID, &msg.AuthorID, &msg.Text, &msg.CreatedAt, &msg.AttachmentIDs)
|
||||
msg.Text = decodeText(msg.Text)
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
return msg, err
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, mapErr(err)
|
||||
}
|
||||
|
||||
page := domain.Page[domain.Message]{}
|
||||
if len(out) > limit {
|
||||
last := out[limit-1]
|
||||
page.NextCursor = domain.EncodeCursor(domain.Cursor{
|
||||
CreatedAt: last.CreatedAt,
|
||||
ID: last.ID,
|
||||
Scope: scope,
|
||||
})
|
||||
out = out[:limit]
|
||||
}
|
||||
page.Items = out
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package db
|
||||
|
||||
import "strings"
|
||||
|
||||
var (
|
||||
textEncoder = strings.NewReplacer(`\`, `\\`, "\x00", `\0`)
|
||||
textDecoder = strings.NewReplacer(`\\`, `\`, `\0`, "\x00")
|
||||
)
|
||||
|
||||
func encodeText(s string) string {
|
||||
if !strings.ContainsAny(s, "\\\x00") {
|
||||
return s
|
||||
}
|
||||
return textEncoder.Replace(s)
|
||||
}
|
||||
|
||||
func decodeText(s string) string {
|
||||
if !strings.Contains(s, `\`) {
|
||||
return s
|
||||
}
|
||||
return textDecoder.Replace(s)
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
type Users struct {
|
||||
conn
|
||||
}
|
||||
|
||||
func (u *Users) CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error) {
|
||||
if strings.TrimSpace(username) == "" || strings.TrimSpace(displayName) == "" || passwordHash == "" {
|
||||
return domain.User{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
ctx, cancel := u.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
user := domain.User{Username: username, DisplayName: displayName}
|
||||
err := u.pool.QueryRow(ctx, `
|
||||
INSERT INTO users (username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id::text, created_at`,
|
||||
username, encodeText(displayName), passwordHash,
|
||||
).Scan(&user.ID, &user.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.User{}, mapErr(err)
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (u *Users) UserByID(ctx context.Context, id string) (domain.User, error) {
|
||||
ctx, cancel := u.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
user := domain.User{}
|
||||
err := u.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 err != nil {
|
||||
err = mapErr(err)
|
||||
if err == domain.ErrInvalidArgument {
|
||||
return domain.User{}, domain.ErrNotFound
|
||||
}
|
||||
return domain.User{}, err
|
||||
}
|
||||
user.DisplayName = decodeText(user.DisplayName)
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (u *Users) CredentialsByUsername(ctx context.Context, username string) (domain.User, string, error) {
|
||||
ctx, cancel := u.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
user := domain.User{}
|
||||
var hash string
|
||||
err := u.pool.QueryRow(ctx, `
|
||||
SELECT id::text, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE username = $1`,
|
||||
encodeText(username),
|
||||
).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash)
|
||||
if err != nil {
|
||||
return domain.User{}, "", mapErr(err)
|
||||
}
|
||||
user.DisplayName = decodeText(user.DisplayName)
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, hash, nil
|
||||
}
|
||||
|
||||
func (u *Users) UsernameExists(ctx context.Context, username string) bool {
|
||||
ctx, cancel := u.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var exists bool
|
||||
err := u.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS (SELECT 1 FROM users WHERE username = $1)`,
|
||||
encodeText(username),
|
||||
).Scan(&exists)
|
||||
return err == nil && exists
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var _ Store = (*Memory)(nil)
|
||||
|
||||
type Memory struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
users map[string]domain.User
|
||||
byName map[string]string
|
||||
hashes map[string]string
|
||||
|
||||
chats map[string]*chatBucket
|
||||
chatOrder []string
|
||||
|
||||
lastTime time.Time
|
||||
|
||||
idempotency map[string]domain.Message
|
||||
|
||||
attachments map[string]domain.Attachment
|
||||
|
||||
maxMessages int
|
||||
messagesTotal int
|
||||
}
|
||||
|
||||
type chatBucket struct {
|
||||
chat domain.Chat
|
||||
members map[string]struct{}
|
||||
messages []domain.Message
|
||||
}
|
||||
|
||||
func New() *Memory {
|
||||
return NewWithLimit(0)
|
||||
}
|
||||
|
||||
func NewWithLimit(maxMessages int) *Memory {
|
||||
return &Memory{
|
||||
users: make(map[string]domain.User),
|
||||
byName: make(map[string]string),
|
||||
hashes: make(map[string]string),
|
||||
chats: make(map[string]*chatBucket),
|
||||
idempotency: make(map[string]domain.Message),
|
||||
attachments: make(map[string]domain.Attachment),
|
||||
maxMessages: maxMessages,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Memory) MessagesTotal() int {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return m.messagesTotal
|
||||
}
|
||||
|
||||
func (m *Memory) now() time.Time {
|
||||
t := time.Now().UTC()
|
||||
if !t.After(m.lastTime) {
|
||||
t = m.lastTime.Add(time.Nanosecond)
|
||||
}
|
||||
m.lastTime = t
|
||||
return t
|
||||
}
|
||||
|
||||
func (m *Memory) CreateUser(_ context.Context, username, displayName, passwordHash string) (domain.User, error) {
|
||||
if strings.TrimSpace(username) == "" || strings.TrimSpace(displayName) == "" {
|
||||
return domain.User{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if _, taken := m.byName[username]; taken {
|
||||
return domain.User{}, domain.ErrConflict
|
||||
}
|
||||
|
||||
u := domain.User{
|
||||
ID: uuid.NewString(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: m.now(),
|
||||
}
|
||||
m.users[u.ID] = u
|
||||
m.byName[username] = u.ID
|
||||
m.hashes[u.ID] = passwordHash
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (m *Memory) UserByID(_ context.Context, id string) (domain.User, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
u, ok := m.users[id]
|
||||
if !ok {
|
||||
return domain.User{}, domain.ErrNotFound
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (m *Memory) CredentialsByUsername(_ context.Context, username string) (domain.User, string, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
id, ok := m.byName[username]
|
||||
if !ok {
|
||||
return domain.User{}, "", domain.ErrNotFound
|
||||
}
|
||||
return m.users[id], m.hashes[id], nil
|
||||
}
|
||||
|
||||
func (m *Memory) UsernameExists(_ context.Context, username string) bool {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
_, taken := m.byName[username]
|
||||
return taken
|
||||
}
|
||||
|
||||
func (m *Memory) CreateChat(_ context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) {
|
||||
if strings.TrimSpace(title) == "" {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
if len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
callerInMembers := false
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if id == callerID {
|
||||
callerInMembers = true
|
||||
}
|
||||
}
|
||||
if !callerInMembers {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
for _, id := range memberIDs {
|
||||
if _, ok := m.users[id]; !ok {
|
||||
return domain.Chat{}, domain.ErrInvalidArgument
|
||||
}
|
||||
}
|
||||
|
||||
members := append([]string(nil), memberIDs...)
|
||||
|
||||
chat := domain.Chat{
|
||||
ID: uuid.NewString(),
|
||||
Title: title,
|
||||
MemberIDs: members,
|
||||
CreatedAt: m.now(),
|
||||
}
|
||||
m.chats[chat.ID] = &chatBucket{
|
||||
chat: chat,
|
||||
members: seen,
|
||||
}
|
||||
m.chatOrder = append(m.chatOrder, chat.ID)
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (m *Memory) ChatByID(_ context.Context, callerID, chatID string) (domain.Chat, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
b, ok := m.chats[chatID]
|
||||
if !ok {
|
||||
return domain.Chat{}, domain.ErrNotFound
|
||||
}
|
||||
if _, member := b.members[callerID]; !member {
|
||||
return domain.Chat{}, domain.ErrNotFound
|
||||
}
|
||||
return cloneChat(b.chat), nil
|
||||
}
|
||||
|
||||
func (m *Memory) ListChats(_ context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) {
|
||||
if limit <= 0 || limit > 100 {
|
||||
return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
c, err := domain.DecodeCursor(cursor)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, err
|
||||
}
|
||||
if cursor != "" && c.Scope != "chats:"+callerID {
|
||||
return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
out := make([]domain.Chat, 0, limit+1)
|
||||
for _, id := range m.chatOrder {
|
||||
b := m.chats[id]
|
||||
if _, member := b.members[callerID]; !member {
|
||||
continue
|
||||
}
|
||||
if !c.Less(b.chat.CreatedAt, b.chat.ID) {
|
||||
continue
|
||||
}
|
||||
out = append(out, cloneChat(b.chat))
|
||||
if len(out) > limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
page := domain.Page[domain.Chat]{}
|
||||
if len(out) > limit {
|
||||
last := out[limit-1]
|
||||
page.NextCursor = domain.EncodeCursor(domain.Cursor{
|
||||
CreatedAt: last.CreatedAt,
|
||||
ID: last.ID,
|
||||
Scope: "chats:" + callerID,
|
||||
})
|
||||
out = out[:limit]
|
||||
}
|
||||
page.Items = out
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (m *Memory) AddMessage(_ context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) {
|
||||
if strings.TrimSpace(text) == "" && len(attachmentIDs) == 0 {
|
||||
return domain.Message{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
b, ok := m.chats[chatID]
|
||||
if !ok {
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
}
|
||||
if _, member := b.members[callerID]; !member {
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
idemKey := callerID + "\x00" + chatID + "\x00" + idempotencyKey
|
||||
if prev, ok := m.idempotency[idemKey]; ok {
|
||||
if prev.Text != text || !slices.Equal(prev.AttachmentIDs, attachmentIDs) {
|
||||
return domain.Message{}, domain.ErrIdempotencyConflict
|
||||
}
|
||||
return prev, nil
|
||||
}
|
||||
|
||||
if m.maxMessages > 0 && m.messagesTotal >= m.maxMessages {
|
||||
return domain.Message{}, domain.ErrUnavailable
|
||||
}
|
||||
|
||||
for _, id := range attachmentIDs {
|
||||
if att, ok := m.attachments[id]; !ok || att.ChatID != chatID {
|
||||
return domain.Message{}, domain.ErrNotFound
|
||||
}
|
||||
}
|
||||
|
||||
msg := domain.Message{
|
||||
ID: uuid.NewString(),
|
||||
ChatID: chatID,
|
||||
AuthorID: callerID,
|
||||
Text: text,
|
||||
CreatedAt: m.now(),
|
||||
AttachmentIDs: attachmentIDs,
|
||||
}
|
||||
b.messages = append(b.messages, msg)
|
||||
m.idempotency[idemKey] = msg
|
||||
m.messagesTotal++
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func (m *Memory) ListMessages(_ context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
if limit <= 0 || limit > 100 {
|
||||
return domain.Page[domain.Message]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
c, err := domain.DecodeCursor(cursor)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
|
||||
if cursor != "" && c.Scope != "chat:"+chatID {
|
||||
return domain.Page[domain.Message]{}, domain.ErrInvalidArgument
|
||||
}
|
||||
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
b, ok := m.chats[chatID]
|
||||
if !ok {
|
||||
return domain.Page[domain.Message]{}, domain.ErrNotFound
|
||||
}
|
||||
if _, member := b.members[callerID]; !member {
|
||||
return domain.Page[domain.Message]{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
start := 0
|
||||
for ; start < len(b.messages); start++ {
|
||||
if c.Less(b.messages[start].CreatedAt, b.messages[start].ID) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
end := start + limit
|
||||
hasMore := end < len(b.messages)
|
||||
if end > len(b.messages) {
|
||||
end = len(b.messages)
|
||||
}
|
||||
|
||||
out := make([]domain.Message, end-start)
|
||||
copy(out, b.messages[start:end])
|
||||
|
||||
page := domain.Page[domain.Message]{Items: out}
|
||||
if hasMore && len(out) > 0 {
|
||||
last := out[len(out)-1]
|
||||
page.NextCursor = domain.EncodeCursor(domain.Cursor{
|
||||
CreatedAt: last.CreatedAt,
|
||||
ID: last.ID,
|
||||
Scope: "chat:" + chatID,
|
||||
})
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (m *Memory) CreateAttachment(_ context.Context, att domain.Attachment) (domain.Attachment, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if b, ok := m.chats[att.ChatID]; !ok {
|
||||
return domain.Attachment{}, domain.ErrNotFound
|
||||
} else if _, member := b.members[att.OwnerID]; !member {
|
||||
return domain.Attachment{}, domain.ErrNotFound
|
||||
}
|
||||
att.CreatedAt = m.now()
|
||||
att.UpdatedAt = att.CreatedAt
|
||||
m.attachments[att.ID] = att
|
||||
return att, nil
|
||||
}
|
||||
|
||||
func (m *Memory) AttachmentForMember(_ context.Context, callerID, attachmentID string) (domain.Attachment, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
att, ok := m.attachments[attachmentID]
|
||||
if !ok {
|
||||
return domain.Attachment{}, domain.ErrNotFound
|
||||
}
|
||||
if _, member := m.chats[att.ChatID].members[callerID]; !member {
|
||||
return domain.Attachment{}, domain.ErrNotFound
|
||||
}
|
||||
return att, nil
|
||||
}
|
||||
|
||||
func (m *Memory) AttachmentExists(_ context.Context, attachmentID string) (bool, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
_, ok := m.attachments[attachmentID]
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
func cloneChat(c domain.Chat) domain.Chat {
|
||||
out := c
|
||||
out.MemberIDs = append([]string(nil), c.MemberIDs...)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
type UserStore interface {
|
||||
CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error)
|
||||
UserByID(ctx context.Context, id string) (domain.User, error)
|
||||
CredentialsByUsername(ctx context.Context, username string) (domain.User, string, error)
|
||||
UsernameExists(ctx context.Context, username string) bool
|
||||
}
|
||||
|
||||
type ChatStore interface {
|
||||
CreateChat(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error)
|
||||
ChatByID(ctx context.Context, callerID, chatID string) (domain.Chat, error)
|
||||
ListChats(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error)
|
||||
}
|
||||
|
||||
type MessageStore interface {
|
||||
// AddMessage идемпотентен по (callerID, chatID, idempotencyKey): повтор с тем же
|
||||
// text и attachmentIDs возвращает исходное сообщение, с другими — domain.ErrIdempotencyConflict.
|
||||
// Вложение не из этого чата или неизвестное — domain.ErrNotFound.
|
||||
AddMessage(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error)
|
||||
ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error)
|
||||
}
|
||||
|
||||
type AttachmentStore interface {
|
||||
CreateAttachment(ctx context.Context, att domain.Attachment) (domain.Attachment, error)
|
||||
// AttachmentForMember для постороннего возвращает domain.ErrNotFound.
|
||||
AttachmentForMember(ctx context.Context, callerID, attachmentID string) (domain.Attachment, error)
|
||||
// AttachmentExists нужен компенсации: ошибка INSERT не доказывает, что строки нет.
|
||||
AttachmentExists(ctx context.Context, attachmentID string) (bool, error)
|
||||
}
|
||||
|
||||
type Store interface {
|
||||
UserStore
|
||||
ChatStore
|
||||
MessageStore
|
||||
AttachmentStore
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const Bytes = 32
|
||||
|
||||
var encoding = base64.RawURLEncoding
|
||||
|
||||
var EncodedLen = encoding.EncodedLen(Bytes)
|
||||
|
||||
var ErrMalformed = errors.New("token: malformed")
|
||||
|
||||
func New() (plain string, hash []byte, err error) {
|
||||
buf := make([]byte, Bytes)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", nil, fmt.Errorf("token: rand: %w", err)
|
||||
}
|
||||
plain = encoding.EncodeToString(buf)
|
||||
return plain, Hash(plain), nil
|
||||
}
|
||||
|
||||
func Hash(plain string) []byte {
|
||||
sum := sha256.Sum256([]byte(plain))
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
func Parse(plain string) ([]byte, error) {
|
||||
if len(plain) != EncodedLen {
|
||||
return nil, ErrMalformed
|
||||
}
|
||||
raw, err := encoding.DecodeString(plain)
|
||||
if err != nil || len(raw) != Bytes {
|
||||
return nil, ErrMalformed
|
||||
}
|
||||
return Hash(plain), nil
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package validate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
FilenameMinLen = 1
|
||||
FilenameMaxLen = 255
|
||||
|
||||
AttachmentIDsMax = 10
|
||||
)
|
||||
|
||||
// Filename проверяет отображаемое имя. Оно нигде не используется как путь, но попадает в заголовки
|
||||
// и к другим клиентам, поэтому разделители и невидимые управляющие символы запрещены.
|
||||
func Filename(s string) error {
|
||||
if !utf8.ValidString(s) {
|
||||
return newError("filename", "must be valid UTF-8")
|
||||
}
|
||||
if !notOnlyWhitespace(s) {
|
||||
return newError("filename", "must not be empty or whitespace only")
|
||||
}
|
||||
if !codePointsBetween(s, FilenameMinLen, FilenameMaxLen) {
|
||||
return newError("filename", fmt.Sprintf("length must be in [%d, %d] code points", FilenameMinLen, FilenameMaxLen))
|
||||
}
|
||||
if s == "." || s == ".." {
|
||||
return newError("filename", "must not be a path component")
|
||||
}
|
||||
if strings.ContainsFunc(s, unsafeFilenameRune) {
|
||||
return newError("filename", "must not contain path separators or control characters")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unsafeFilenameRune(r rune) bool {
|
||||
switch {
|
||||
case r == '/', r == '\\', unicode.IsControl(r):
|
||||
return true
|
||||
case r == '
', r == '
':
|
||||
return true
|
||||
case r >= '' && r <= '', r >= '' && r <= '':
|
||||
// Символы смены направления текста позволяют выдать evil.exe за безобидное имя.
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AttachmentIDs приводит ID к каноничному виду с сохранением порядка.
|
||||
func AttachmentIDs(ids []string) ([]string, error) {
|
||||
if len(ids) > AttachmentIDsMax {
|
||||
return nil, newError("attachment_ids", fmt.Sprintf("count must be at most %d", AttachmentIDsMax))
|
||||
}
|
||||
out := make([]string, 0, len(ids))
|
||||
seen := make(map[string]struct{}, len(ids))
|
||||
for i, raw := range ids {
|
||||
id, err := CanonicalUUID(fmt.Sprintf("attachment_ids[%d]", i), raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
return nil, newError("attachment_ids", "must not contain duplicates")
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
out = append(out, id)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package validate
|
||||
|
||||
import "fmt"
|
||||
|
||||
func ChatTitle(s string) error {
|
||||
if !notOnlyWhitespace(s) {
|
||||
return newError("title", "must not be empty or whitespace only")
|
||||
}
|
||||
if !codePointsBetween(s, ChatTitleMinLen, ChatTitleMaxLen) {
|
||||
return newError("title", fmt.Sprintf("length must be in [%d, %d] code points", ChatTitleMinLen, ChatTitleMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func MemberIDs(ids []string, callerID string) ([]string, error) {
|
||||
if len(ids) < MemberIDsMin || len(ids) > MemberIDsMax {
|
||||
return nil, newError("member_ids", fmt.Sprintf("count must be in [%d, %d]", MemberIDsMin, MemberIDsMax))
|
||||
}
|
||||
|
||||
out := make([]string, 0, len(ids))
|
||||
seen := make(map[string]struct{}, len(ids))
|
||||
callerIn := false
|
||||
for i, raw := range ids {
|
||||
id, err := CanonicalUUID(fmt.Sprintf("member_ids[%d]", i), raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
return nil, newError("member_ids", "must not contain duplicates")
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if id == callerID {
|
||||
callerIn = true
|
||||
}
|
||||
out = append(out, id)
|
||||
}
|
||||
|
||||
if !callerIn {
|
||||
return nil, newError("member_ids", "must contain caller")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package validate
|
||||
|
||||
import "regexp"
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func IdempotencyKey(s string) error {
|
||||
if !idempotencyKeyPattern.MatchString(s) {
|
||||
return newError("Idempotency-Key", "must match [A-Za-z0-9._:-]{1,128}")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package validate
|
||||
|
||||
import "fmt"
|
||||
|
||||
// MessageText: пустой или пробельный текст допустим, только если у сообщения есть вложения.
|
||||
func MessageText(s string, hasAttachments bool) error {
|
||||
if !hasAttachments && !notOnlyWhitespace(s) {
|
||||
return newError("text", "must not be empty or whitespace only")
|
||||
}
|
||||
if !codePointsBetween(s, 0, MessageTextMaxLen) {
|
||||
return newError("text", fmt.Sprintf("length must be at most %d code points", MessageTextMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package validate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
UsernameMinLen = 3
|
||||
UsernameMaxLen = 32
|
||||
|
||||
DisplayNameMinLen = 1
|
||||
DisplayNameMaxLen = 100
|
||||
|
||||
PasswordMinLen = 12
|
||||
PasswordMaxLen = 128
|
||||
|
||||
ChatTitleMinLen = 1
|
||||
ChatTitleMaxLen = 100
|
||||
|
||||
MessageTextMaxLen = 4000
|
||||
|
||||
MemberIDsMin = 1
|
||||
MemberIDsMax = 100
|
||||
|
||||
LimitMin = 1
|
||||
LimitMax = 100
|
||||
LimitDefault = 50
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func CanonicalUUID(field, s string) (string, error) {
|
||||
if len(s) != 36 {
|
||||
return "", newError(field, "must be a valid UUID")
|
||||
}
|
||||
u, err := uuid.Parse(s)
|
||||
if err != nil {
|
||||
return "", newError(field, "must be a valid UUID")
|
||||
}
|
||||
return u.String(), nil
|
||||
}
|
||||
|
||||
func Limit(n int) error {
|
||||
if n < LimitMin || n > LimitMax {
|
||||
return newError("limit", fmt.Sprintf("must be in [%d, %d]", LimitMin, LimitMax))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func codePointsBetween(s string, min, max int) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= min && n <= max
|
||||
}
|
||||
|
||||
func notOnlyWhitespace(s string) bool {
|
||||
return strings.TrimSpace(s) != ""
|
||||
}
|
||||
|
||||
type Error struct {
|
||||
Field string
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (e *Error) Error() string {
|
||||
return e.Field + ": " + e.Reason
|
||||
}
|
||||
|
||||
func (e *Error) Is(target error) bool {
|
||||
_, ok := target.(*Error)
|
||||
return ok
|
||||
}
|
||||
|
||||
func newError(field, reason string) *Error {
|
||||
return &Error{Field: field, Reason: reason}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package validate
|
||||
|
||||
import "fmt"
|
||||
|
||||
func Username(s string) error {
|
||||
if !usernamePattern.MatchString(s) {
|
||||
return newError("username", fmt.Sprintf("must match [a-z0-9_]{%d,%d}", UsernameMinLen, UsernameMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func DisplayName(s string) error {
|
||||
if !notOnlyWhitespace(s) {
|
||||
return newError("display_name", "must not be empty or whitespace only")
|
||||
}
|
||||
if !codePointsBetween(s, DisplayNameMinLen, DisplayNameMaxLen) {
|
||||
return newError("display_name", fmt.Sprintf("length must be in [%d, %d] code points", DisplayNameMinLen, DisplayNameMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Password(s string) error {
|
||||
if !notOnlyWhitespace(s) {
|
||||
return newError("password", "must not be empty or whitespace only")
|
||||
}
|
||||
if !codePointsBetween(s, PasswordMinLen, PasswordMaxLen) {
|
||||
return newError("password", fmt.Sprintf("length must be in [%d, %d] code points", PasswordMinLen, PasswordMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user