forked from mtusi2026/mtusi2026lab4
S3-вложения и сверка Postgresql с MinIO
This commit is contained in:
@@ -0,0 +1,415 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrIdempotencyMismatch = errors.New("idempotency mismatch")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrInvalid = errors.New("invalid")
|
||||
ErrBadCursor = errors.New("bad cursor")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
ErrNotReady = errors.New("attachment not ready")
|
||||
)
|
||||
|
||||
// User — публичная карточка. Хеш пароля в неё не входит.
|
||||
type User struct {
|
||||
ID string
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Chat — неизменяемый состав участников.
|
||||
type Chat struct {
|
||||
ID string
|
||||
Title string
|
||||
MemberIDs []string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Message — подтверждённое сообщение. Текст после записи не меняется.
|
||||
type Message struct {
|
||||
ID string
|
||||
ChatID string
|
||||
SenderID string
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
AttachmentIDs []string
|
||||
}
|
||||
|
||||
// Attachment — метаданные файла. ObjectKey наружу API не отдаётся.
|
||||
type Attachment struct {
|
||||
ID string
|
||||
ChatID string
|
||||
OwnerID string
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
ObjectKey string
|
||||
Width int
|
||||
Height int
|
||||
Status string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// AttachmentRef — строка для сверки с bucket.
|
||||
type AttachmentRef struct {
|
||||
ID string
|
||||
ObjectKey string
|
||||
CreatedAt time.Time
|
||||
Referenced bool
|
||||
}
|
||||
|
||||
// Cursor — позиция keyset (created_at, id). Пустые поля означают первую страницу.
|
||||
type Cursor struct {
|
||||
ID string
|
||||
At time.Time
|
||||
}
|
||||
|
||||
// Repository — пользователи, чаты и сообщения. Сессии сюда не входят.
|
||||
type Repository interface {
|
||||
Ping(ctx context.Context) error
|
||||
CreateUser(ctx context.Context, username, displayName, passwordHash string) (User, error)
|
||||
User(ctx context.Context, id string) (User, error)
|
||||
UserByUsername(ctx context.Context, username string) (User, string, error)
|
||||
CreateChat(ctx context.Context, title string, memberIDs []string, caller string) (Chat, error)
|
||||
ChatFor(ctx context.Context, chatID, userID string) (Chat, error)
|
||||
ListChats(ctx context.Context, userID string, cur *Cursor, limit int) ([]Chat, bool, error)
|
||||
// AddMessage создаёт сообщение или возвращает уже записанное для того же ключа.
|
||||
// fingerprint — каноническое тело. Другой fingerprint при живом ключе даёт ErrIdempotencyMismatch.
|
||||
// Ключ живёт idempotencyTTL. Область: отправитель + чат + ключ (метод POST и путь чата).
|
||||
// Чужое или неизвестное вложение — ErrNotFound. Неготовое — ErrNotReady.
|
||||
AddMessage(ctx context.Context, chatID, senderID, text string, attachmentIDs []string, idemKey, fingerprint string) (Message, error)
|
||||
ListMessages(ctx context.Context, chatID, userID string, cur *Cursor, limit int) ([]Message, bool, error)
|
||||
InsertAttachment(ctx context.Context, row Attachment) (Attachment, error)
|
||||
AttachmentVisible(ctx context.Context, id, userID string) (Attachment, error)
|
||||
AttachmentRefs(ctx context.Context) ([]AttachmentRef, error)
|
||||
DeleteUnreferencedAttachment(ctx context.Context, id string, olderThan time.Time) (bool, error)
|
||||
}
|
||||
|
||||
type chatRec struct {
|
||||
chat Chat
|
||||
members map[string]struct{}
|
||||
}
|
||||
|
||||
type idemRec struct {
|
||||
fingerprint string
|
||||
messageID string
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
// Memory сериализует записи мьютексом. Это двойник контракта для тестов без PostgreSQL.
|
||||
type Memory struct {
|
||||
mu sync.RWMutex
|
||||
users map[string]User
|
||||
byName map[string]string
|
||||
hashes map[string]string
|
||||
chats map[string]*chatRec
|
||||
chatOrder []string
|
||||
messages map[string][]Message
|
||||
msgIndex map[string]map[string]int
|
||||
attachments map[string]Attachment
|
||||
referenced map[string]struct{}
|
||||
idem map[string]idemRec
|
||||
idemTTL time.Duration
|
||||
last time.Time
|
||||
}
|
||||
|
||||
func New() *Memory {
|
||||
return &Memory{
|
||||
users: make(map[string]User),
|
||||
byName: make(map[string]string),
|
||||
hashes: make(map[string]string),
|
||||
chats: make(map[string]*chatRec),
|
||||
messages: make(map[string][]Message),
|
||||
msgIndex: make(map[string]map[string]int),
|
||||
attachments: make(map[string]Attachment),
|
||||
referenced: make(map[string]struct{}),
|
||||
idem: make(map[string]idemRec),
|
||||
idemTTL: 24 * time.Hour,
|
||||
}
|
||||
}
|
||||
|
||||
// SetIdempotencyTTL меняет срок ключа. Нужен тестам; в PostgreSQL тот же смысл у IDEMPOTENCY_TTL_SECONDS.
|
||||
func (s *Memory) SetIdempotencyTTL(d time.Duration) {
|
||||
if d <= 0 {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.idemTTL = d
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Memory) Ping(ctx context.Context) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Memory) CreateUser(ctx context.Context, username, displayName, passwordHash string) (User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return User{}, ErrUnavailable
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.byName[username]; ok {
|
||||
return User{}, ErrConflict
|
||||
}
|
||||
u := User{
|
||||
ID: newID(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: s.nextTimeLocked(),
|
||||
}
|
||||
s.users[u.ID] = u
|
||||
s.byName[username] = u.ID
|
||||
s.hashes[u.ID] = passwordHash
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *Memory) User(ctx context.Context, id string) (User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return User{}, ErrUnavailable
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
u, ok := s.users[id]
|
||||
if !ok {
|
||||
return User{}, ErrNotFound
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *Memory) UserByUsername(ctx context.Context, username string) (User, string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return User{}, "", ErrUnavailable
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
id, ok := s.byName[username]
|
||||
if !ok {
|
||||
return User{}, "", ErrNotFound
|
||||
}
|
||||
return s.users[id], s.hashes[id], nil
|
||||
}
|
||||
|
||||
func (s *Memory) CreateChat(ctx context.Context, title string, memberIDs []string, caller string) (Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Chat{}, ErrUnavailable
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return Chat{}, ErrInvalid
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if _, ok := s.users[id]; !ok {
|
||||
return Chat{}, ErrInvalid
|
||||
}
|
||||
}
|
||||
if _, ok := seen[caller]; !ok {
|
||||
return Chat{}, ErrInvalid
|
||||
}
|
||||
c := Chat{
|
||||
ID: newID(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
CreatedAt: s.nextTimeLocked(),
|
||||
}
|
||||
s.chats[c.ID] = &chatRec{chat: c, members: seen}
|
||||
s.chatOrder = append(s.chatOrder, c.ID)
|
||||
s.messages[c.ID] = nil
|
||||
s.msgIndex[c.ID] = make(map[string]int)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *Memory) ChatFor(ctx context.Context, chatID, userID string) (Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Chat{}, ErrUnavailable
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
rec, ok := s.chats[chatID]
|
||||
if !ok {
|
||||
return Chat{}, ErrNotFound
|
||||
}
|
||||
if _, member := rec.members[userID]; !member {
|
||||
return Chat{}, ErrNotFound
|
||||
}
|
||||
return rec.chat.clone(), nil
|
||||
}
|
||||
|
||||
func (s *Memory) ListChats(ctx context.Context, userID string, cur *Cursor, limit int) ([]Chat, bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, false, ErrUnavailable
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
filtered := make([]Chat, 0)
|
||||
for _, id := range s.chatOrder {
|
||||
rec := s.chats[id]
|
||||
if _, ok := rec.members[userID]; ok {
|
||||
filtered = append(filtered, rec.chat.clone())
|
||||
}
|
||||
}
|
||||
start, err := indexAfter(filtered, cur, func(c Chat) (string, time.Time) {
|
||||
return c.ID, c.CreatedAt
|
||||
})
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
end := start + limit
|
||||
if end > len(filtered) {
|
||||
end = len(filtered)
|
||||
}
|
||||
return append([]Chat(nil), filtered[start:end]...), end < len(filtered), nil
|
||||
}
|
||||
|
||||
func (s *Memory) AddMessage(ctx context.Context, chatID, senderID, text string, attachmentIDs []string, idemKey, fingerprint string) (Message, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Message{}, ErrUnavailable
|
||||
}
|
||||
if idemKey == "" || fingerprint == "" {
|
||||
return Message{}, ErrInvalid
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
rec, ok := s.chats[chatID]
|
||||
if !ok {
|
||||
return Message{}, ErrNotFound
|
||||
}
|
||||
if _, member := rec.members[senderID]; !member {
|
||||
return Message{}, ErrNotFound
|
||||
}
|
||||
slot := senderID + "\x00" + chatID + "\x00" + idemKey
|
||||
if prev, ok := s.idem[slot]; ok && prev.expires.After(time.Now()) {
|
||||
if prev.fingerprint != fingerprint {
|
||||
return Message{}, ErrIdempotencyMismatch
|
||||
}
|
||||
idx, ok := s.msgIndex[chatID][prev.messageID]
|
||||
if !ok {
|
||||
return Message{}, ErrNotFound
|
||||
}
|
||||
return s.messages[chatID][idx], nil
|
||||
}
|
||||
ids := append([]string(nil), attachmentIDs...)
|
||||
for _, id := range ids {
|
||||
row, ok := s.attachments[id]
|
||||
if !ok || row.ChatID != chatID {
|
||||
return Message{}, ErrNotFound
|
||||
}
|
||||
if row.Status != "ready" {
|
||||
return Message{}, ErrNotReady
|
||||
}
|
||||
}
|
||||
m := Message{
|
||||
ID: newID(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: s.nextTimeLocked(),
|
||||
AttachmentIDs: ids,
|
||||
}
|
||||
if m.AttachmentIDs == nil {
|
||||
m.AttachmentIDs = []string{}
|
||||
}
|
||||
idx := len(s.messages[chatID])
|
||||
s.messages[chatID] = append(s.messages[chatID], m)
|
||||
s.msgIndex[chatID][m.ID] = idx
|
||||
s.idem[slot] = idemRec{fingerprint: fingerprint, messageID: m.ID, expires: time.Now().Add(s.idemTTL)}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (s *Memory) ListMessages(ctx context.Context, chatID, userID string, cur *Cursor, limit int) ([]Message, bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, false, ErrUnavailable
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
rec, ok := s.chats[chatID]
|
||||
if !ok {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
if _, member := rec.members[userID]; !member {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
all := s.messages[chatID]
|
||||
start := 0
|
||||
if cur != nil {
|
||||
idx, ok := s.msgIndex[chatID][cur.ID]
|
||||
if !ok || !all[idx].CreatedAt.Equal(cur.At) {
|
||||
return nil, false, ErrBadCursor
|
||||
}
|
||||
start = idx + 1
|
||||
}
|
||||
end := start + limit
|
||||
if end > len(all) {
|
||||
end = len(all)
|
||||
}
|
||||
out := append([]Message(nil), all[start:end]...)
|
||||
return out, end < len(all), nil
|
||||
}
|
||||
|
||||
// nextTimeLocked выдаёт неубывающее время фиксации.
|
||||
func (s *Memory) nextTimeLocked() time.Time {
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
if !now.After(s.last) {
|
||||
now = s.last.Add(time.Microsecond)
|
||||
}
|
||||
s.last = now
|
||||
return now
|
||||
}
|
||||
|
||||
func indexAfter[T any](items []T, cur *Cursor, key func(T) (string, time.Time)) (int, error) {
|
||||
if cur == nil {
|
||||
return 0, nil
|
||||
}
|
||||
for i, item := range items {
|
||||
id, at := key(item)
|
||||
if id == cur.ID {
|
||||
if !at.Equal(cur.At) {
|
||||
return 0, ErrBadCursor
|
||||
}
|
||||
return i + 1, nil
|
||||
}
|
||||
}
|
||||
return 0, ErrBadCursor
|
||||
}
|
||||
|
||||
func (c Chat) clone() Chat {
|
||||
c.MemberIDs = append([]string(nil), c.MemberIDs...)
|
||||
return c
|
||||
}
|
||||
|
||||
func newID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic("crypto/rand: " + err.Error())
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
var buf [36]byte
|
||||
hex.Encode(buf[0:8], b[0:4])
|
||||
buf[8] = '-'
|
||||
hex.Encode(buf[9:13], b[4:6])
|
||||
buf[13] = '-'
|
||||
hex.Encode(buf[14:18], b[6:8])
|
||||
buf[18] = '-'
|
||||
hex.Encode(buf[19:23], b[8:10])
|
||||
buf[23] = '-'
|
||||
hex.Encode(buf[24:36], b[10:16])
|
||||
return string(buf[:])
|
||||
}
|
||||
Reference in New Issue
Block a user