lab5: очередь RabbitMQ, outbox, worker, варианты, fault-injection
This commit is contained in:
@@ -0,0 +1,370 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg" // DecodeConfig для раннего отказа по размерам
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/imagecheck"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
"github.com/charawein/mtusi2026lab5/internal/storage"
|
||||
)
|
||||
|
||||
// Раскладка bucket (все ключи назначает сервер, filename в них не попадает):
|
||||
//
|
||||
// s/{chat}/{id} — staging: проверенный оригинал до обработки
|
||||
// o/{chat}/{id} — опубликованный оригинал (worker копирует из staging)
|
||||
// v/{chat}/{id}/p{ver}/{variant} — варианты версии pipeline ver
|
||||
// a/{chat}/{id} — оригиналы lab4 (остаются на месте)
|
||||
const (
|
||||
ObjectPrefix = "a/"
|
||||
StagingPrefix = "s/"
|
||||
OriginalPrefix = "o/"
|
||||
VariantPrefix = "v/"
|
||||
)
|
||||
|
||||
type AttachmentRepository interface {
|
||||
CreateIntent(ctx context.Context, a *domain.Attachment) error
|
||||
MarkQueued(ctx context.Context, a *domain.Attachment, pipelineVersion, maxAttempts int) (string, error)
|
||||
DeleteIntent(ctx context.Context, id string) error
|
||||
GetForMember(ctx context.Context, id, userID string) (*domain.Attachment, error)
|
||||
Variants(ctx context.Context, attachmentID string, version int) ([]domain.Variant, error)
|
||||
}
|
||||
|
||||
type AttachmentService struct {
|
||||
repo AttachmentRepository
|
||||
chats repository.ChatRepository
|
||||
store storage.Store
|
||||
maxBytes int64
|
||||
maxPixels int64
|
||||
pipelineVersion int
|
||||
maxAttempts int
|
||||
}
|
||||
|
||||
func NewAttachmentService(repo AttachmentRepository, chats repository.ChatRepository, store storage.Store, maxBytes, maxPixels int64, pipelineVersion, maxAttempts int) *AttachmentService {
|
||||
return &AttachmentService{repo: repo, chats: chats, store: store, maxBytes: maxBytes, maxPixels: maxPixels,
|
||||
pipelineVersion: pipelineVersion, maxAttempts: maxAttempts}
|
||||
}
|
||||
|
||||
// validateFilename: 1–255 code points, не только пробелы, без / \ NUL и управляющих.
|
||||
func validateFilename(s string) bool {
|
||||
if !utf8.ValidString(s) || strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
if n := utf8.RuneCountInString(s); n < 1 || n > 255 {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if r == '/' || r == '\\' || r == 0 || unicode.IsControl(r) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// declaredType нормализует Content-Type запроса; допустимы только PNG/JPEG.
|
||||
func declaredType(h string) (string, bool) {
|
||||
mt, _, err := mime.ParseMediaType(h)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
mt = strings.ToLower(mt)
|
||||
return mt, mt == imagecheck.PNG || mt == imagecheck.JPEG
|
||||
}
|
||||
|
||||
// Upload принимает сырые байты одного изображения и возвращает снимок queued (202).
|
||||
//
|
||||
// Порядок: намерение в PostgreSQL (uploading) → потоковый PUT в S3-staging,
|
||||
// параллельно SHA-256 и структурная проверка изображения → ОДНА транзакция:
|
||||
// status=queued + задание + сообщение outbox. 202 возвращается только после
|
||||
// COMMIT: в этот момент устойчиво сохранены проверенный оригинал (staging),
|
||||
// метаданные и намерение обработки; broker для 202 не нужен (outbox опубликует).
|
||||
//
|
||||
// Ошибка до MarkQueued (проверка, PUT, обрыв клиента) компенсируется сразу:
|
||||
// удаляются объект и намерение. Ошибка самого MarkQueued — неопределённый исход
|
||||
// (COMMIT мог пройти): объект НЕ удаляется; остаток uploading+объект уберёт
|
||||
// reconciler после grace. Состояния «queued без оригинала» не бывает.
|
||||
func (s *AttachmentService) Upload(ctx context.Context, ownerID, chatID, filename, contentType string, body io.Reader, contentLength int64) (*domain.Attachment, error) {
|
||||
parsed, err := uuid.Parse(chatID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
chatID = parsed.String()
|
||||
ok, err := s.chats.IsMember(ctx, chatID, ownerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if !validateFilename(filename) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
declared, ok := declaredType(contentType)
|
||||
if !ok {
|
||||
return nil, ErrUnsupportedMedia
|
||||
}
|
||||
// Лимит размера — до чтения тела.
|
||||
if contentLength > s.maxBytes {
|
||||
return nil, ErrPayloadTooLarge
|
||||
}
|
||||
size := contentLength
|
||||
if size < 0 {
|
||||
// Без Content-Length (chunked): буфер не больше лимита + 1 байт.
|
||||
buf, err := io.ReadAll(io.LimitReader(body, s.maxBytes+1))
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if int64(len(buf)) > s.maxBytes {
|
||||
return nil, ErrPayloadTooLarge
|
||||
}
|
||||
body, size = bytes.NewReader(buf), int64(len(buf))
|
||||
}
|
||||
if size == 0 {
|
||||
return nil, ErrUnsupportedMedia
|
||||
}
|
||||
|
||||
// Формат — по содержимому; подмена Content-Type → 415.
|
||||
br := bufio.NewReaderSize(body, 64*1024)
|
||||
head, _ := br.Peek(int(min(size, 64*1024)))
|
||||
format, ok := imagecheck.Sniff(head)
|
||||
if !ok || format != declared {
|
||||
return nil, ErrUnsupportedMedia
|
||||
}
|
||||
// Ранний отказ по пикселям, если заголовок уместился в первые 64 KiB.
|
||||
if cfg, _, err := image.DecodeConfig(bytes.NewReader(head)); err == nil {
|
||||
if int64(cfg.Width)*int64(cfg.Height) > s.maxPixels {
|
||||
return nil, ErrPayloadTooLarge
|
||||
}
|
||||
}
|
||||
|
||||
now := nowUTC()
|
||||
id := newID()
|
||||
a := &domain.Attachment{
|
||||
ID: id, ChatID: chatID, OwnerID: ownerID, Filename: filename,
|
||||
ObjectKey: StagingPrefix + chatID + "/" + id,
|
||||
Status: domain.AttachmentUploading, CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
if err := s.repo.CreateIntent(ctx, a); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sum, putErr := s.putValidated(ctx, a.ObjectKey, br, size, format)
|
||||
if putErr != nil {
|
||||
s.compensate(ctx, a, putErr)
|
||||
return nil, putErr
|
||||
}
|
||||
|
||||
a.Status = domain.AttachmentQueued
|
||||
a.ContentType = format
|
||||
a.SizeBytes = size
|
||||
a.SHA256 = sum
|
||||
a.StagingKey = a.ObjectKey
|
||||
a.UpdatedAt = nowUTC()
|
||||
// Байты уже сохранены: доводим учёт до конца, даже если клиент отвалился.
|
||||
mctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
if _, err := s.repo.MarkQueued(mctx, a, s.pipelineVersion, s.maxAttempts); err != nil {
|
||||
s.markReadyFailed(ctx, a, err)
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
var errClientBody = errors.New("request body read failed")
|
||||
|
||||
// trackingReader запоминает ошибку чтения, отличную от EOF.
|
||||
type trackingReader struct {
|
||||
r io.Reader
|
||||
err error
|
||||
}
|
||||
|
||||
func (t *trackingReader) Read(p []byte) (int, error) {
|
||||
n, err := t.r.Read(p)
|
||||
if err != nil && err != io.EOF {
|
||||
t.err = err
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
type bodyReader struct{ r io.Reader }
|
||||
|
||||
func (b bodyReader) Read(p []byte) (int, error) {
|
||||
n, err := b.r.Read(p)
|
||||
if err != nil && err != io.EOF {
|
||||
return n, errors.Join(errClientBody, err)
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// putValidated пишет объект в S3 и одновременно проверяет изображение и считает
|
||||
// SHA-256. Байты проходят потоком (pipe), в памяти — только буферы чтения.
|
||||
func (s *AttachmentService) putValidated(ctx context.Context, key string, body io.Reader, size int64, format string) (string, error) {
|
||||
pr, pw := io.Pipe()
|
||||
valErr := make(chan error, 1)
|
||||
go func() {
|
||||
tr := &trackingReader{r: pr}
|
||||
_, err := imagecheck.Validate(tr, format, s.maxPixels)
|
||||
if tr.err != nil {
|
||||
// Поток оборвали снаружи (PUT в S3 упал или клиент отвалился):
|
||||
// изображение тут ни при чём, причину определит putErr.
|
||||
valErr <- nil
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
pr.CloseWithError(err) // прерывает PUT: дальше писать некуда
|
||||
}
|
||||
valErr <- err
|
||||
}()
|
||||
|
||||
h := sha256.New()
|
||||
src := io.TeeReader(io.TeeReader(bodyReader{body}, h), pw)
|
||||
putErr := s.store.Put(ctx, key, src, size, format)
|
||||
if putErr != nil {
|
||||
pw.CloseWithError(putErr)
|
||||
} else {
|
||||
pw.Close()
|
||||
}
|
||||
vErr := <-valErr
|
||||
|
||||
switch {
|
||||
case errors.Is(vErr, imagecheck.ErrTooLarge):
|
||||
return "", ErrPayloadTooLarge
|
||||
case errors.Is(vErr, imagecheck.ErrInvalid):
|
||||
return "", ErrUnsupportedMedia
|
||||
case errors.Is(putErr, errClientBody):
|
||||
return "", ErrInvalidInput
|
||||
case putErr != nil:
|
||||
slog.Warn("attachment upload to s3 failed", "err", putErr)
|
||||
return "", ErrUnavailable
|
||||
case vErr != nil:
|
||||
return "", ErrUnsupportedMedia
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// markReadyFailed: исход UPDATE неизвестен — объект оставляем. Пробуем убрать
|
||||
// намерение (DELETE ... WHERE status='uploading' безопасен при любом исходе:
|
||||
// если UPDATE уже закоммичен, он ничего не удалит). Если и это не удалось —
|
||||
// uploading+объект уберёт reconciler после grace period.
|
||||
func (s *AttachmentService) markReadyFailed(ctx context.Context, a *domain.Attachment, cause error) {
|
||||
cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := s.repo.DeleteIntent(cctx, a.ID); err != nil {
|
||||
slog.Warn("mark ready failed, intent left for reconciler", "attachment_id", a.ID, "cause", cause.Error(), "err", err)
|
||||
return
|
||||
}
|
||||
slog.Warn("mark ready failed, object left for reconciler", "attachment_id", a.ID, "cause", cause.Error())
|
||||
}
|
||||
|
||||
// compensate убирает следы неудачной загрузки. Работает и после обрыва клиента
|
||||
// (контекст запроса отменён), поэтому использует отдельный контекст.
|
||||
func (s *AttachmentService) compensate(ctx context.Context, a *domain.Attachment, cause error) {
|
||||
cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := s.store.Delete(cctx, a.ObjectKey); err != nil {
|
||||
slog.Warn("compensation: delete object failed, reconciler will retry", "attachment_id", a.ID, "err", err)
|
||||
}
|
||||
if err := s.repo.DeleteIntent(cctx, a.ID); err != nil {
|
||||
slog.Warn("compensation: delete intent failed, reconciler will retry", "attachment_id", a.ID, "err", err)
|
||||
}
|
||||
slog.Info("attachment upload compensated", "attachment_id", a.ID, "cause", cause.Error())
|
||||
}
|
||||
|
||||
// Get возвращает метаданные вложения участнику его чата (queued/processing/
|
||||
// ready/failed); у ready — варианты опубликованной версии pipeline.
|
||||
func (s *AttachmentService) Get(ctx context.Context, userID, id string) (*domain.Attachment, error) {
|
||||
parsed, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
a, err := s.repo.GetForMember(ctx, parsed.String(), userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
switch a.Status {
|
||||
case domain.AttachmentReady:
|
||||
if a.PipelineVersion > 0 {
|
||||
if a.Variants, err = s.repo.Variants(ctx, a.ID, a.PipelineVersion); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return a, nil
|
||||
case domain.AttachmentQueued, domain.AttachmentProcessing, domain.AttachmentFailed:
|
||||
return a, nil
|
||||
case domain.AttachmentMissing:
|
||||
// Метаданные есть, байтов нет (обнаружил reconciler): ошибка сервера, не клиента.
|
||||
return nil, ErrUnavailable
|
||||
default:
|
||||
return nil, ErrNotFound // загрузка не завершена — объекта для клиента ещё нет
|
||||
}
|
||||
}
|
||||
|
||||
// Content — что отдавать клиенту: тип, размер и ключ объекта.
|
||||
type Content struct {
|
||||
ContentType string
|
||||
Size int64
|
||||
Key string
|
||||
}
|
||||
|
||||
// Open открывает оригинал или вариант на чтение. Вызывающий закрывает ReadCloser.
|
||||
// queued/processing/failed → 409 (объект не готов), отсутствующий у ready
|
||||
// вариант → 404.
|
||||
func (s *AttachmentService) Open(ctx context.Context, userID, id, variant string) (*Content, io.ReadCloser, error) {
|
||||
a, err := s.Get(ctx, userID, id)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if a.Status != domain.AttachmentReady {
|
||||
return nil, nil, ErrConflict
|
||||
}
|
||||
c := &Content{ContentType: a.ContentType, Size: a.SizeBytes, Key: a.ObjectKey}
|
||||
if variant != "" && variant != "original" {
|
||||
c = nil
|
||||
for _, v := range a.Variants {
|
||||
if v.Name == variant {
|
||||
c = &Content{ContentType: v.ContentType, Size: v.SizeBytes, Key: v.ObjectKey}
|
||||
}
|
||||
}
|
||||
if c == nil {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
}
|
||||
rc, size, err := s.store.Get(ctx, c.Key)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
slog.Error("attachment object missing in s3", "attachment_id", a.ID)
|
||||
} else {
|
||||
slog.Warn("s3 get failed", "attachment_id", a.ID, "err", err)
|
||||
}
|
||||
return nil, nil, ErrUnavailable
|
||||
}
|
||||
if size != c.Size {
|
||||
rc.Close()
|
||||
slog.Error("attachment size mismatch", "attachment_id", a.ID, "variant", variant, "s3", size, "db", c.Size)
|
||||
return nil, nil, ErrUnavailable
|
||||
}
|
||||
return c, rc, nil
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/storage"
|
||||
)
|
||||
|
||||
// failingStore читает failAfter байт и падает — как PUT в недоступный S3.
|
||||
type failingStore struct {
|
||||
storage.Store
|
||||
failAfter int64
|
||||
got []byte
|
||||
}
|
||||
|
||||
func (f *failingStore) Put(_ context.Context, _ string, r io.Reader, size int64, _ string) error {
|
||||
if f.failAfter < 0 {
|
||||
b, err := io.ReadAll(r)
|
||||
f.got = b
|
||||
return err
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(r, f.failAfter))
|
||||
f.got = b
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return errors.New("s3 put: connection refused")
|
||||
}
|
||||
|
||||
type errReader struct{ data []byte }
|
||||
|
||||
func (e *errReader) Read(p []byte) (int, error) {
|
||||
if len(e.data) == 0 {
|
||||
return 0, errors.New("connection reset by peer")
|
||||
}
|
||||
n := copy(p, e.data)
|
||||
e.data = e.data[n:]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func samplePNG(t *testing.T) []byte {
|
||||
img := image.NewRGBA(image.Rect(0, 0, 200, 150))
|
||||
for y := 0; y < 150; y++ {
|
||||
for x := 0; x < 200; x++ {
|
||||
img.Set(x, y, color.RGBA{uint8(x), uint8(y), uint8(x ^ y), 255})
|
||||
}
|
||||
}
|
||||
var b bytes.Buffer
|
||||
if err := png.Encode(&b, img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func TestPutValidatedClassifiesCause(t *testing.T) {
|
||||
data := samplePNG(t)
|
||||
size := int64(len(data))
|
||||
svc := &AttachmentService{maxBytes: 10 << 20, maxPixels: 40_000_000}
|
||||
|
||||
// S3 падает посреди потока: это 503, а не «битое изображение».
|
||||
svc.store = &failingStore{failAfter: size / 3}
|
||||
if _, err := svc.putValidated(context.Background(), "k", bytes.NewReader(data), size, "image/png"); !errors.Is(err, ErrUnavailable) {
|
||||
t.Errorf("s3 failure mid-stream: got %v, want ErrUnavailable", err)
|
||||
}
|
||||
// S3 падает сразу.
|
||||
svc.store = &failingStore{failAfter: 0}
|
||||
if _, err := svc.putValidated(context.Background(), "k", bytes.NewReader(data), size, "image/png"); !errors.Is(err, ErrUnavailable) {
|
||||
t.Errorf("s3 failure at start: got %v, want ErrUnavailable", err)
|
||||
}
|
||||
// Клиент оборвал тело: 400, не 415 и не 503.
|
||||
svc.store = &failingStore{failAfter: -1}
|
||||
if _, err := svc.putValidated(context.Background(), "k", &errReader{data: data[:len(data)/2]}, size, "image/png"); !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("client body error: got %v, want ErrInvalidInput", err)
|
||||
}
|
||||
// Битое изображение при исправном S3: 415.
|
||||
bad := bytes.Clone(data)
|
||||
bad[len(bad)/2] ^= 0xFF
|
||||
svc.store = &failingStore{failAfter: -1}
|
||||
if _, err := svc.putValidated(context.Background(), "k", bytes.NewReader(bad), size, "image/png"); !errors.Is(err, ErrUnsupportedMedia) {
|
||||
t.Errorf("corrupt image: got %v, want ErrUnsupportedMedia", err)
|
||||
}
|
||||
// Всё хорошо: SHA-256 и байты целиком дошли до S3.
|
||||
ok := &failingStore{failAfter: -1}
|
||||
svc.store = ok
|
||||
sum, err := svc.putValidated(context.Background(), "k", bytes.NewReader(data), size, "image/png")
|
||||
if err != nil || len(sum) != 64 || !bytes.Equal(ok.got, data) {
|
||||
t.Errorf("valid upload: sum=%q err=%v bytes_equal=%v", sum, err, bytes.Equal(ok.got, data))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type AuthService struct {
|
||||
users repository.UserRepository
|
||||
sessions repository.SessionRepository
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewAuthService(users repository.UserRepository, sessions repository.SessionRepository, ttl time.Duration) *AuthService {
|
||||
return &AuthService{users: users, sessions: sessions, ttl: ttl}
|
||||
}
|
||||
|
||||
func (s *AuthService) Login(ctx context.Context, username, password string) (*domain.Session, *domain.User, error) {
|
||||
u, err := s.users.GetByUsername(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
_, _ = hashPassword("dummy-password-for-timing")
|
||||
return nil, nil, ErrUnauthorized
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
hash, err := s.users.GetPasswordHash(ctx, u.ID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if err := verifyPassword(password, hash); err != nil {
|
||||
if errors.Is(err, ErrPasswordMismatch) {
|
||||
return nil, nil, ErrUnauthorized
|
||||
}
|
||||
return nil, nil, fmt.Errorf("verify password: %w", err)
|
||||
}
|
||||
|
||||
token, err := generateToken()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("generate token: %w", err)
|
||||
}
|
||||
|
||||
now := nowUTC()
|
||||
sess := &domain.Session{
|
||||
Token: token,
|
||||
UserID: u.ID,
|
||||
ExpiresAt: now.Add(s.ttl),
|
||||
CreatedAt: now,
|
||||
}
|
||||
if err := s.sessions.Create(ctx, sess); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return sess, u, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) ValidateSession(ctx context.Context, token string) (*domain.User, error) {
|
||||
sess, err := s.sessions.GetByToken(ctx, token)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
// Redis недоступен — возвращаем 401, чтобы клиент перелогинился,
|
||||
// либо 503, если хотим явно показать проблему зависимости.
|
||||
return nil, ErrUnauthorized // ← было: return nil, err
|
||||
}
|
||||
if nowUTC().After(sess.ExpiresAt) {
|
||||
_ = s.sessions.Delete(ctx, token)
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
u, err := s.users.GetByID(ctx, sess.UserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) Logout(ctx context.Context, token string) error {
|
||||
return s.sessions.Delete(ctx, token)
|
||||
}
|
||||
|
||||
func generateToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type ChatService struct {
|
||||
chats repository.ChatRepository
|
||||
users repository.UserRepository
|
||||
}
|
||||
|
||||
func NewChatService(chats repository.ChatRepository, users repository.UserRepository) *ChatService {
|
||||
return &ChatService{chats: chats, users: users}
|
||||
}
|
||||
|
||||
func (s *ChatService) Create(ctx context.Context, callerID, title string, memberIDs []string) (*domain.Chat, error) {
|
||||
if !validateTitle(title) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
// Нормализация UUID: убираем разницу регистра.
|
||||
normalized := make([]string, 0, len(memberIDs))
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
callerFound := false
|
||||
callerParsed, err := uuid.Parse(callerID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
callerID = callerParsed.String()
|
||||
|
||||
for _, id := range memberIDs {
|
||||
parsed, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
id = parsed.String()
|
||||
if _, dup := seen[id]; dup {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
normalized = append(normalized, id)
|
||||
if id == callerID {
|
||||
callerFound = true
|
||||
}
|
||||
}
|
||||
if !callerFound {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
for id := range seen {
|
||||
if _, err := s.users.GetByID(ctx, id); err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
c := &domain.Chat{
|
||||
ID: newID(),
|
||||
Title: title,
|
||||
MemberIDs: normalized,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if err := s.chats.Create(ctx, c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) Get(ctx context.Context, callerID, chatID string) (*domain.Chat, error) {
|
||||
parsed, err := uuid.Parse(chatID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
chatID = parsed.String()
|
||||
|
||||
ok, err := s.chats.IsMember(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
c, err := s.chats.GetByID(ctx, chatID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *ChatService) List(ctx context.Context, callerID, cursor string, limit int) ([]*domain.Chat, string, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, "", ErrInvalidInput
|
||||
}
|
||||
|
||||
cursorTime := time.Unix(0, 0).UTC()
|
||||
cursorID := "00000000-0000-0000-0000-000000000000"
|
||||
if cursor != "" {
|
||||
t, id, err := decodeCursor(cursor, callerID)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
cursorTime, cursorID = t, id
|
||||
}
|
||||
|
||||
items, err := s.chats.ListByMember(ctx, callerID, cursorTime, cursorID, limit+1)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if items == nil {
|
||||
items = []*domain.Chat{}
|
||||
}
|
||||
|
||||
var next string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[limit-1]
|
||||
next = encodeCursor(callerID, last.CreatedAt, last.ID)
|
||||
}
|
||||
return items, next, nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func encodeCursor(scope string, createdAt time.Time, id string) string {
|
||||
raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func decodeCursor(cursor, expectedScope string) (time.Time, string, error) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
parts := strings.SplitN(string(raw), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
if _, err := uuid.Parse(parts[0]); err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
if parts[0] != expectedScope {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
if _, err := uuid.Parse(parts[2]); err != nil {
|
||||
return time.Time{}, "", ErrInvalidInput
|
||||
}
|
||||
return t, parts[2], nil
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package service
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
ErrPasswordMismatch = errors.New("password mismatch")
|
||||
ErrPayloadTooLarge = errors.New("payload too large")
|
||||
ErrUnsupportedMedia = errors.New("unsupported media type")
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic(fmt.Sprintf("crypto/rand failed: %v", err))
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
|
||||
}
|
||||
|
||||
// nowUTC возвращает время UTC с точностью до секунд.
|
||||
// PostgreSQL и Python-клиент тестов ожидают формат без наносекунд.
|
||||
func nowUTC() time.Time {
|
||||
return time.Now().UTC().Truncate(time.Second)
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
redisrepo "github.com/charawein/mtusi2026lab5/internal/repository/redis"
|
||||
)
|
||||
|
||||
type MessageService struct {
|
||||
messages repository.MessageRepository
|
||||
chats repository.ChatRepository
|
||||
cache *redisrepo.MessageCache
|
||||
idempotencyTTL time.Duration
|
||||
}
|
||||
|
||||
func NewMessageService(messages repository.MessageRepository, chats repository.ChatRepository, cache *redisrepo.MessageCache, idempotencyTTL time.Duration) *MessageService {
|
||||
return &MessageService{messages: messages, chats: chats, cache: cache, idempotencyTTL: idempotencyTTL}
|
||||
}
|
||||
|
||||
var idempotencyKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
// requestHash — отпечаток семантики тела запроса. Хешируем уже разобранные поля,
|
||||
// а не сырые байты: порядок ключей JSON не важен, отсутствующий attachment_ids
|
||||
// равен [], порядок самих вложений значим.
|
||||
func requestHash(text string, attachmentIDs []string) string {
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
raw, _ := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}{Text: text, AttachmentIDs: attachmentIDs})
|
||||
sum := sha256.Sum256(raw)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// Send создаёт сообщение с обязательным Idempotency-Key. Повтор с тем же ключом
|
||||
// и телом возвращает исходное сообщение, с другим телом — ErrConflict.
|
||||
// Доступ к чату проверяется при каждом повторе.
|
||||
func (s *MessageService) Send(ctx context.Context, senderID, chatID, text string, attachmentIDs []string, idempotencyKey string) (*domain.Message, error) {
|
||||
if !idempotencyKeyRe.MatchString(idempotencyKey) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
parsed, err := uuid.Parse(chatID)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
chatID = parsed.String()
|
||||
|
||||
ids, ok := normalizeAttachmentIDs(attachmentIDs)
|
||||
if !ok {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
// С вложениями допустим пустой text; иначе — обычные правила текста.
|
||||
if !(len(ids) > 0 && text == "") && !validateText(text) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
ok, err = s.chats.IsMember(ctx, chatID, senderID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
m := &domain.Message{
|
||||
ID: newID(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
|
||||
AttachmentIDs: ids,
|
||||
}
|
||||
stored, created, err := s.messages.CreateIdempotent(ctx, m, idempotencyKey, requestHash(text, ids), s.idempotencyTTL)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, repository.ErrConflict):
|
||||
return nil, ErrConflict
|
||||
case errors.Is(err, repository.ErrNotFound):
|
||||
return nil, ErrNotFound // чужое/неизвестное/незавершённое вложение
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if !created {
|
||||
return stored, nil
|
||||
}
|
||||
|
||||
// Версия чата уже увеличена в транзакции записи; здесь только режим scan.
|
||||
if s.cache != nil {
|
||||
s.cache.OnWrite(ctx, chatID)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (s *MessageService) List(ctx context.Context, callerID, chatID, cursor string, limit int) ([]*domain.Message, string, error) {
|
||||
parsed, err := uuid.Parse(chatID)
|
||||
if err != nil {
|
||||
return nil, "", ErrInvalidInput
|
||||
}
|
||||
chatID = parsed.String()
|
||||
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, "", ErrInvalidInput
|
||||
}
|
||||
|
||||
// Членство и версия истории — одним запросом к PostgreSQL. Версия читается
|
||||
// до истории, поэтому под ключом версии v лежат данные не старее v.
|
||||
version, ok, err := s.chats.MemberVersion(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, "", ErrNotFound
|
||||
}
|
||||
return nil, "", err
|
||||
}
|
||||
if !ok {
|
||||
return nil, "", ErrNotFound
|
||||
}
|
||||
|
||||
if s.cache != nil {
|
||||
if items, next, hit := s.cache.Get(ctx, chatID, version, cursor, limit); hit {
|
||||
return items, next, nil
|
||||
}
|
||||
}
|
||||
|
||||
cursorTime := time.Unix(0, 0).UTC()
|
||||
cursorID := "00000000-0000-0000-0000-000000000000"
|
||||
if cursor != "" {
|
||||
t, id, err := decodeCursor(cursor, chatID)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
cursorTime, cursorID = t, id
|
||||
}
|
||||
|
||||
items, err := s.messages.ListByChat(ctx, chatID, cursorTime, cursorID, limit+1)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if items == nil {
|
||||
items = []*domain.Message{}
|
||||
}
|
||||
|
||||
var next string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[limit-1]
|
||||
next = encodeCursor(chatID, last.CreatedAt, last.ID)
|
||||
}
|
||||
|
||||
if s.cache != nil {
|
||||
s.cache.Set(ctx, chatID, version, cursor, limit, items, next)
|
||||
}
|
||||
return items, next, nil
|
||||
}
|
||||
|
||||
// normalizeAttachmentIDs: 0–10 уникальных UUID; приводит к каноническому виду.
|
||||
func normalizeAttachmentIDs(in []string) ([]string, bool) {
|
||||
if len(in) > 10 {
|
||||
return nil, false
|
||||
}
|
||||
out := make([]string, 0, len(in))
|
||||
seen := make(map[string]bool, len(in))
|
||||
for _, raw := range in {
|
||||
u, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
id := u.String()
|
||||
if seen[id] {
|
||||
return nil, false
|
||||
}
|
||||
seen[id] = true
|
||||
out = append(out, id)
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonTime = 1
|
||||
argonMemory = 64 * 1024
|
||||
argonThreads = 4
|
||||
argonKeyLen = 32
|
||||
argonSaltLen = 16
|
||||
)
|
||||
|
||||
func hashPassword(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate salt: %w", err)
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
return fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemory, argonTime, argonThreads,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(hash),
|
||||
), nil
|
||||
}
|
||||
|
||||
func verifyPassword(password, encoded string) error {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return fmt.Errorf("invalid hash format")
|
||||
}
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
return fmt.Errorf("parse version: %w", err)
|
||||
}
|
||||
if version != argon2.Version {
|
||||
return fmt.Errorf("incompatible version: %d", version)
|
||||
}
|
||||
var mem uint32
|
||||
var iters uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &mem, &iters, &threads); err != nil {
|
||||
return fmt.Errorf("parse params: %w", err)
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode salt: %w", err)
|
||||
}
|
||||
want, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode hash: %w", err)
|
||||
}
|
||||
got := argon2.IDKey([]byte(password), salt, iters, mem, threads, uint32(len(want)))
|
||||
if subtle.ConstantTimeCompare(got, want) != 1 {
|
||||
return ErrPasswordMismatch
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/charawein/mtusi2026lab5/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab5/internal/repository"
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
users repository.UserRepository
|
||||
}
|
||||
|
||||
func NewUserService(users repository.UserRepository) *UserService {
|
||||
return &UserService{users: users}
|
||||
}
|
||||
|
||||
// Register создаёт нового пользователя. Возвращает ErrInvalidInput при невалидных
|
||||
// данных и ErrConflict, если username занят.
|
||||
func (s *UserService) Register(ctx context.Context, username, displayName, password string) (*domain.User, error) {
|
||||
if !validateUsername(username) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if !validateDisplayName(displayName) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if !validatePassword(password) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
hash, err := hashPassword(password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hash password: %w", err)
|
||||
}
|
||||
|
||||
u := &domain.User{
|
||||
ID: newID(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if err := s.users.Create(ctx, u, hash); err != nil {
|
||||
if errors.Is(err, repository.ErrConflict) {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// GetByID возвращает пользователя. Возвращает ErrNotFound, если такого нет.
|
||||
// Используется middleware аутентификации для проверки X-User-Id.
|
||||
func (s *UserService) GetByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
u, err := s.users.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
// validatePassword: 12–128 code points и не только пробельные символы
|
||||
// (обязательная строка по контракту не может состоять из одних пробелов).
|
||||
func validatePassword(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 12 && n <= 128
|
||||
}
|
||||
|
||||
// validateUsername проверяет формат username по README: строго [a-z0-9_]{3,32}.
|
||||
func validateUsername(s string) bool {
|
||||
return usernameRe.MatchString(s)
|
||||
}
|
||||
|
||||
// validateDisplayName проверяет display_name: 1–100 Unicode code points,
|
||||
// не состоит только из пробельных символов.
|
||||
func validateDisplayName(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 100
|
||||
}
|
||||
|
||||
// validateTitle проверяет title чата: 1–100 code points, не только пробелы.
|
||||
func validateTitle(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 100
|
||||
}
|
||||
|
||||
// validateText проверяет text сообщения: 1–4000 code points, не только пробелы.
|
||||
// В lab4 появится возможность отправить пустой text, если есть attachment_ids.
|
||||
func validateText(s string) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 1 && n <= 4000
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidatePassword(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
in string
|
||||
want bool
|
||||
}{
|
||||
{"обычный", "correct-horse-12", true},
|
||||
{"ровно 12", strings.Repeat("a", 12), true},
|
||||
{"128 code points", strings.Repeat("я", 128), true},
|
||||
{"двоеточие допустимо", "pass:word:1234", true},
|
||||
{"пробелы внутри допустимы", " pass word ", true},
|
||||
{"короче 12", strings.Repeat("a", 11), false},
|
||||
{"длиннее 128", strings.Repeat("a", 129), false},
|
||||
{"12 пробелов", strings.Repeat(" ", 12), false},
|
||||
{"пробельные символы разных видов", strings.Repeat(" \t\n ", 4), false},
|
||||
{"пусто", "", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := validatePassword(c.in); got != c.want {
|
||||
t.Errorf("%s: validatePassword(%q) = %v, want %v", c.name, c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateText(t *testing.T) {
|
||||
if validateText(strings.Repeat(" ", 5)) {
|
||||
t.Error("whitespace-only text must be rejected")
|
||||
}
|
||||
if !validateText("привет") {
|
||||
t.Error("normal text must be accepted")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user