forked from mtusi2026/mtusi2026lab4
S3-вложения и сверка Postgresql с MinIO
This commit is contained in:
@@ -0,0 +1,286 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (p *PG) InsertAttachment(ctx context.Context, row Attachment) (Attachment, error) {
|
||||
if row.ID == "" {
|
||||
row.ID = newID()
|
||||
}
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
if row.CreatedAt.IsZero() {
|
||||
row.CreatedAt = now
|
||||
} else {
|
||||
row.CreatedAt = row.CreatedAt.UTC().Truncate(time.Microsecond)
|
||||
}
|
||||
row.UpdatedAt = row.CreatedAt
|
||||
row.Status = "ready"
|
||||
_, err := p.pool.Exec(ctx, `
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, width, height, status, created_at, updated_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13
|
||||
)`,
|
||||
row.ID, row.ChatID, row.OwnerID, row.Filename, row.ContentType, row.SizeBytes, row.SHA256,
|
||||
row.ObjectKey, row.Width, row.Height, row.Status, row.CreatedAt, row.UpdatedAt)
|
||||
if err != nil {
|
||||
return Attachment{}, mapDB(err)
|
||||
}
|
||||
return row, nil
|
||||
}
|
||||
|
||||
func (p *PG) AttachmentVisible(ctx context.Context, id, userID string) (Attachment, error) {
|
||||
var row Attachment
|
||||
err := p.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.width, a.height, a.status, a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2
|
||||
WHERE a.id = $1`, id, userID).Scan(
|
||||
&row.ID, &row.ChatID, &row.OwnerID, &row.Filename, &row.ContentType,
|
||||
&row.SizeBytes, &row.SHA256, &row.ObjectKey, &row.Width, &row.Height, &row.Status,
|
||||
&row.CreatedAt, &row.UpdatedAt)
|
||||
if err != nil {
|
||||
return Attachment{}, mapDB(err)
|
||||
}
|
||||
row.CreatedAt = row.CreatedAt.UTC()
|
||||
row.UpdatedAt = row.UpdatedAt.UTC()
|
||||
return row, nil
|
||||
}
|
||||
|
||||
func (p *PG) AttachmentRefs(ctx context.Context) ([]AttachmentRef, error) {
|
||||
rows, err := p.pool.Query(ctx, `
|
||||
SELECT a.id::text, a.object_key, a.created_at,
|
||||
EXISTS(SELECT 1 FROM message_attachments m WHERE m.attachment_id = a.id)
|
||||
FROM attachments a`)
|
||||
if err != nil {
|
||||
return nil, mapDB(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
out := make([]AttachmentRef, 0)
|
||||
for rows.Next() {
|
||||
var row AttachmentRef
|
||||
if err := rows.Scan(&row.ID, &row.ObjectKey, &row.CreatedAt, &row.Referenced); err != nil {
|
||||
return nil, mapDB(err)
|
||||
}
|
||||
row.CreatedAt = row.CreatedAt.UTC()
|
||||
out = append(out, row)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, mapDB(err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (p *PG) DeleteUnreferencedAttachment(ctx context.Context, id string, olderThan time.Time) (bool, error) {
|
||||
tag, err := p.pool.Exec(ctx, `
|
||||
DELETE FROM attachments a
|
||||
WHERE a.id = $1
|
||||
AND a.created_at < $2
|
||||
AND NOT EXISTS (SELECT 1 FROM message_attachments m WHERE m.attachment_id = a.id)`, id, olderThan)
|
||||
if err != nil {
|
||||
return false, mapDB(err)
|
||||
}
|
||||
return tag.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
func bindAttachments(ctx context.Context, tx pgx.Tx, messageID, chatID string, ids []string) error {
|
||||
for i, id := range ids {
|
||||
var gotChat, status string
|
||||
err := tx.QueryRow(ctx, `
|
||||
SELECT chat_id::text, status FROM attachments WHERE id = $1`, id).Scan(&gotChat, &status)
|
||||
if err != nil {
|
||||
if mapDB(err) == ErrNotFound {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if gotChat != chatID {
|
||||
return ErrNotFound
|
||||
}
|
||||
if status != "ready" {
|
||||
return ErrNotReady
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
VALUES ($1, $2, $3)`, messageID, id, i); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func attachmentIDsOf(ctx context.Context, q queryer, messageID string) ([]string, error) {
|
||||
rows, err := q.Query(ctx, `
|
||||
SELECT attachment_id::text
|
||||
FROM message_attachments
|
||||
WHERE message_id = $1
|
||||
ORDER BY position`, messageID)
|
||||
if err != nil {
|
||||
return nil, mapDB(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
ids := make([]string, 0)
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, mapDB(err)
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, mapDB(err)
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func fillAttachmentIDs(ctx context.Context, q queryer, items []Message) error {
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]string, len(items))
|
||||
for i := range items {
|
||||
ids[i] = items[i].ID
|
||||
items[i].AttachmentIDs = []string{}
|
||||
}
|
||||
rows, err := q.Query(ctx, `
|
||||
SELECT message_id::text, attachment_id::text
|
||||
FROM message_attachments
|
||||
WHERE message_id::text = ANY($1::text[])
|
||||
ORDER BY message_id, position`, ids)
|
||||
if err != nil {
|
||||
return mapDB(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
grouped := map[string][]string{}
|
||||
for rows.Next() {
|
||||
var messageID, attachmentID string
|
||||
if err := rows.Scan(&messageID, &attachmentID); err != nil {
|
||||
return mapDB(err)
|
||||
}
|
||||
grouped[messageID] = append(grouped[messageID], attachmentID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return mapDB(err)
|
||||
}
|
||||
for i := range items {
|
||||
if got, ok := grouped[items[i].ID]; ok {
|
||||
items[i].AttachmentIDs = got
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Memory) InsertAttachment(ctx context.Context, row Attachment) (Attachment, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Attachment{}, ErrUnavailable
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if row.ID == "" {
|
||||
row.ID = newID()
|
||||
}
|
||||
now := s.nextTimeLocked()
|
||||
if row.CreatedAt.IsZero() {
|
||||
row.CreatedAt = now
|
||||
} else {
|
||||
row.CreatedAt = row.CreatedAt.UTC()
|
||||
}
|
||||
row.UpdatedAt = row.CreatedAt
|
||||
if row.Status == "" {
|
||||
row.Status = "ready"
|
||||
}
|
||||
s.attachments[row.ID] = row
|
||||
return row, nil
|
||||
}
|
||||
|
||||
func (s *Memory) AttachmentVisible(ctx context.Context, id, userID string) (Attachment, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Attachment{}, ErrUnavailable
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
row, ok := s.attachments[id]
|
||||
if !ok {
|
||||
return Attachment{}, ErrNotFound
|
||||
}
|
||||
rec, ok := s.chats[row.ChatID]
|
||||
if !ok {
|
||||
return Attachment{}, ErrNotFound
|
||||
}
|
||||
if _, member := rec.members[userID]; !member {
|
||||
return Attachment{}, ErrNotFound
|
||||
}
|
||||
return row, nil
|
||||
}
|
||||
|
||||
func (s *Memory) AttachmentRefs(ctx context.Context) ([]AttachmentRef, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
out := make([]AttachmentRef, 0, len(s.attachments))
|
||||
for _, row := range s.attachments {
|
||||
out = append(out, AttachmentRef{
|
||||
ID: row.ID, ObjectKey: row.ObjectKey, CreatedAt: row.CreatedAt, Referenced: s.referencedLocked(row.ID),
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Memory) DeleteUnreferencedAttachment(ctx context.Context, id string, olderThan time.Time) (bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return false, ErrUnavailable
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
row, ok := s.attachments[id]
|
||||
if !ok || s.referencedLocked(row.ID) || !row.CreatedAt.Before(olderThan) {
|
||||
return false, nil
|
||||
}
|
||||
delete(s.attachments, id)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// MarkReferenced нужен тесту сверки: строка считается используемой без сообщения.
|
||||
func (s *Memory) MarkReferenced(id string) {
|
||||
s.mu.Lock()
|
||||
s.referenced[id] = struct{}{}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// AttachmentByID читает строку без проверки участника. Только для тестов сверки.
|
||||
func (s *Memory) AttachmentByID(ctx context.Context, id string) (Attachment, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Attachment{}, ErrUnavailable
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
row, ok := s.attachments[id]
|
||||
if !ok {
|
||||
return Attachment{}, ErrNotFound
|
||||
}
|
||||
return row, nil
|
||||
}
|
||||
|
||||
func (s *Memory) referencedLocked(id string) bool {
|
||||
if _, ok := s.referenced[id]; ok {
|
||||
return true
|
||||
}
|
||||
for _, msgs := range s.messages {
|
||||
for _, m := range msgs {
|
||||
for _, aid := range m.AttachmentIDs {
|
||||
if aid == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// PG - источник истины для пользователей, чатов и сообщений.
|
||||
// Запросы только с параметрами. Пул ограничен, у сессии соединения есть statement_timeout.
|
||||
type PG struct {
|
||||
pool *pgxpool.Pool
|
||||
idemTTL time.Duration
|
||||
}
|
||||
|
||||
func Open(ctx context.Context, databaseURL string, maxConns int32) (*PG, error) {
|
||||
cfg, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if maxConns < 1 {
|
||||
maxConns = 10
|
||||
}
|
||||
cfg.MaxConns = maxConns
|
||||
cfg.MinConns = 1
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.HealthCheckPeriod = 30 * time.Second
|
||||
cfg.ConnConfig.ConnectTimeout = 3 * time.Second
|
||||
cfg.ConnConfig.RuntimeParams["application_name"] = "messenger"
|
||||
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
|
||||
cfg.ConnConfig.RuntimeParams["lock_timeout"] = "3000"
|
||||
cfg.ConnConfig.RuntimeParams["idle_in_transaction_session_timeout"] = "10000"
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &PG{pool: pool, idemTTL: 24 * time.Hour}, nil
|
||||
}
|
||||
|
||||
// SetIdempotencyTTL задаёт, сколько хранить результат POST сообщения.
|
||||
func (p *PG) SetIdempotencyTTL(ttl time.Duration) {
|
||||
if ttl > 0 {
|
||||
p.idemTTL = ttl
|
||||
}
|
||||
}
|
||||
|
||||
func (p *PG) Close() { p.pool.Close() }
|
||||
|
||||
func (p *PG) Pool() *pgxpool.Pool { return p.pool }
|
||||
|
||||
func (p *PG) Ping(ctx context.Context) error {
|
||||
return mapDB(p.pool.Ping(ctx))
|
||||
}
|
||||
|
||||
func (p *PG) CreateUser(ctx context.Context, username, displayName, passwordHash string) (User, error) {
|
||||
u := User{
|
||||
ID: newID(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
_, err := p.pool.Exec(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
u.ID, u.Username, u.DisplayName, passwordHash, u.CreatedAt)
|
||||
if err != nil {
|
||||
return User{}, mapDB(err)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (p *PG) User(ctx context.Context, id string) (User, error) {
|
||||
row := p.pool.QueryRow(ctx, `
|
||||
SELECT id::text, username, display_name, created_at
|
||||
FROM users WHERE id = $1`, id)
|
||||
return scanUser(row)
|
||||
}
|
||||
|
||||
func (p *PG) UserByUsername(ctx context.Context, username string) (User, string, error) {
|
||||
var u User
|
||||
var hash string
|
||||
err := p.pool.QueryRow(ctx, `
|
||||
SELECT id::text, username, display_name, created_at, password_hash
|
||||
FROM users WHERE username = $1`, username).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash)
|
||||
if err != nil {
|
||||
return User{}, "", mapDB(err)
|
||||
}
|
||||
u.CreatedAt = u.CreatedAt.UTC()
|
||||
return u, hash, nil
|
||||
}
|
||||
|
||||
// CreateChat пишет чат и всех участников в одной транзакции.
|
||||
// Если кого-то из списка нет, COMMIT не случается и строка чата не остаётся.
|
||||
func (p *PG) CreateChat(ctx context.Context, title string, memberIDs []string, caller string) (Chat, error) {
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return Chat{}, ErrInvalid
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
if _, ok := seen[caller]; !ok {
|
||||
return Chat{}, ErrInvalid
|
||||
}
|
||||
tx, err := p.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return Chat{}, mapDB(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
c := Chat{
|
||||
ID: newID(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`, c.ID, c.Title, c.CreatedAt); err != nil {
|
||||
return Chat{}, mapDB(err)
|
||||
}
|
||||
var n int
|
||||
if err := tx.QueryRow(ctx, `SELECT count(*) FROM users WHERE id::text = ANY($1::text[])`, memberIDs).Scan(&n); err != nil {
|
||||
return Chat{}, mapDB(err)
|
||||
}
|
||||
if n != len(memberIDs) {
|
||||
return Chat{}, ErrInvalid
|
||||
}
|
||||
for i, id := range memberIDs {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO chat_members (chat_id, user_id, position) VALUES ($1, $2, $3)`,
|
||||
c.ID, id, i); err != nil {
|
||||
return Chat{}, mapDB(err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return Chat{}, mapDB(err)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (p *PG) ChatFor(ctx context.Context, chatID, userID string) (Chat, error) {
|
||||
var c Chat
|
||||
err := p.pool.QueryRow(ctx, `
|
||||
SELECT c.id::text, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = $2
|
||||
WHERE c.id = $1`, chatID, userID).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if err != nil {
|
||||
return Chat{}, mapDB(err)
|
||||
}
|
||||
c.CreatedAt = c.CreatedAt.UTC()
|
||||
ids, err := p.memberIDs(ctx, p.pool, []string{c.ID})
|
||||
if err != nil {
|
||||
return Chat{}, err
|
||||
}
|
||||
c.MemberIDs = ids[c.ID]
|
||||
if c.MemberIDs == nil {
|
||||
c.MemberIDs = []string{}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (p *PG) ListChats(ctx context.Context, userID string, cur *Cursor, limit int) ([]Chat, bool, error) {
|
||||
hasCursor := cur != nil
|
||||
at := time.Time{}
|
||||
var id any
|
||||
if hasCursor {
|
||||
at = cur.At
|
||||
id = cur.ID
|
||||
}
|
||||
rows, err := p.pool.Query(ctx, `
|
||||
SELECT c.id::text, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = $1
|
||||
WHERE NOT $2::bool OR (c.created_at, c.id) > ($3::timestamptz, $4::uuid)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $5`, userID, hasCursor, at, id, limit+1)
|
||||
if err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]Chat, 0)
|
||||
ids := make([]string, 0)
|
||||
for rows.Next() {
|
||||
var c Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
c.CreatedAt = c.CreatedAt.UTC()
|
||||
items = append(items, c)
|
||||
ids = append(ids, c.ID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
hasMore := len(items) > limit
|
||||
if hasMore {
|
||||
items = items[:limit]
|
||||
ids = ids[:limit]
|
||||
}
|
||||
members, err := p.memberIDs(ctx, p.pool, ids)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
for i := range items {
|
||||
items[i].MemberIDs = members[items[i].ID]
|
||||
if items[i].MemberIDs == nil {
|
||||
items[i].MemberIDs = []string{}
|
||||
}
|
||||
}
|
||||
return items, hasMore, nil
|
||||
}
|
||||
|
||||
func (p *PG) AddMessage(ctx context.Context, chatID, senderID, text string, attachmentIDs []string, idemKey, fingerprint string) (Message, error) {
|
||||
if idemKey == "" || fingerprint == "" {
|
||||
return Message{}, ErrInvalid
|
||||
}
|
||||
var last error
|
||||
for attempt := 0; attempt < 5; attempt++ {
|
||||
msg, retry, err := p.addMessageOnce(ctx, chatID, senderID, text, attachmentIDs, idemKey, fingerprint)
|
||||
if !retry {
|
||||
return msg, err
|
||||
}
|
||||
last = err
|
||||
}
|
||||
if last == nil {
|
||||
last = ErrUnavailable
|
||||
}
|
||||
return Message{}, ErrUnavailable
|
||||
}
|
||||
|
||||
// addMessageOnce пишет сообщение и ключ одной транзакцией.
|
||||
// retry=true значит, что параллельная реплика заняла тот же ключ раньше: свою вставку откатываем и читаем её результат.
|
||||
func (p *PG) addMessageOnce(ctx context.Context, chatID, senderID, text string, attachmentIDs []string, idemKey, fingerprint string) (Message, bool, error) {
|
||||
tx, err := p.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
var member int
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, senderID).Scan(&member); err != nil {
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
|
||||
var storedFP, messageID string
|
||||
var expires time.Time
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT fingerprint, message_id::text, expires_at
|
||||
FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND idem_key = $3
|
||||
FOR UPDATE`, senderID, chatID, idemKey).Scan(&storedFP, &messageID, &expires)
|
||||
if err == nil {
|
||||
if expires.After(time.Now()) {
|
||||
if storedFP != fingerprint {
|
||||
return Message{}, false, ErrIdempotencyMismatch
|
||||
}
|
||||
msg, err := scanMessage(tx.QueryRow(ctx, `
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages WHERE id = $1`, messageID))
|
||||
if err != nil {
|
||||
return Message{}, false, err
|
||||
}
|
||||
msg.AttachmentIDs, err = attachmentIDsOf(ctx, tx, msg.ID)
|
||||
if err != nil {
|
||||
return Message{}, false, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
return msg, false, nil
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
DELETE FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND idem_key = $3`, senderID, chatID, idemKey); err != nil {
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
} else if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return Message{}, false, mapDB(err)
|
||||
}
|
||||
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
m := Message{
|
||||
ID: newID(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: now,
|
||||
AttachmentIDs: append([]string(nil), attachmentIDs...),
|
||||
}
|
||||
if m.AttachmentIDs == nil {
|
||||
m.AttachmentIDs = []string{}
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`, m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt); err != nil {
|
||||
return Message{}, retryable(err), mapDB(err)
|
||||
}
|
||||
if err := bindAttachments(ctx, tx, m.ID, chatID, m.AttachmentIDs); err != nil {
|
||||
return Message{}, retryable(err), mapDB(err)
|
||||
}
|
||||
recorded := time.Now().UTC().Truncate(time.Microsecond)
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_idempotency
|
||||
(user_id, chat_id, idem_key, fingerprint, message_id, created_at, expires_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
||||
senderID, chatID, idemKey, fingerprint, m.ID, recorded, recorded.Add(p.idemTTL)); err != nil {
|
||||
return Message{}, retryable(err), mapDB(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return Message{}, retryable(err), mapDB(err)
|
||||
}
|
||||
return m, false, nil
|
||||
}
|
||||
|
||||
func retryable(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case "23505", "40001", "40P01":
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *PG) ListMessages(ctx context.Context, chatID, userID string, cur *Cursor, limit int) ([]Message, bool, error) {
|
||||
var member int
|
||||
err := p.pool.QueryRow(ctx, `
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, userID).Scan(&member)
|
||||
if err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
if cur != nil {
|
||||
var one int
|
||||
err := p.pool.QueryRow(ctx, `
|
||||
SELECT 1 FROM messages
|
||||
WHERE chat_id = $1 AND id = $2 AND created_at = $3`, chatID, cur.ID, cur.At).Scan(&one)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, false, ErrBadCursor
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
}
|
||||
hasCursor := cur != nil
|
||||
at := time.Time{}
|
||||
var id any
|
||||
if hasCursor {
|
||||
at = cur.At
|
||||
id = cur.ID
|
||||
}
|
||||
rows, err := p.pool.Query(ctx, `
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (NOT $2::bool OR (created_at, id) > ($3::timestamptz, $4::uuid))
|
||||
ORDER BY created_at, id
|
||||
LIMIT $5`, chatID, hasCursor, at, id, limit+1)
|
||||
if err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]Message, 0)
|
||||
for rows.Next() {
|
||||
m, err := scanMessage(rows)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
items = append(items, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
hasMore := len(items) > limit
|
||||
if hasMore {
|
||||
items = items[:limit]
|
||||
}
|
||||
if err := fillAttachmentIDs(ctx, p.pool, items); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return items, hasMore, nil
|
||||
}
|
||||
|
||||
type queryer interface {
|
||||
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
|
||||
}
|
||||
|
||||
func (p *PG) memberIDs(ctx context.Context, q queryer, chatIDs []string) (map[string][]string, error) {
|
||||
out := make(map[string][]string, len(chatIDs))
|
||||
if len(chatIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
rows, err := q.Query(ctx, `
|
||||
SELECT chat_id::text, user_id::text
|
||||
FROM chat_members
|
||||
WHERE chat_id::text = ANY($1::text[])
|
||||
ORDER BY chat_id, position`, chatIDs)
|
||||
if err != nil {
|
||||
return nil, mapDB(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var chatID, userID string
|
||||
if err := rows.Scan(&chatID, &userID); err != nil {
|
||||
return nil, mapDB(err)
|
||||
}
|
||||
out[chatID] = append(out[chatID], userID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, mapDB(err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func scanMessage(row pgx.Row) (Message, error) {
|
||||
var m Message
|
||||
if err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
}
|
||||
m.CreatedAt = m.CreatedAt.UTC()
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func scanUser(row pgx.Row) (User, error) {
|
||||
var u User
|
||||
err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if err != nil {
|
||||
return User{}, mapDB(err)
|
||||
}
|
||||
u.CreatedAt = u.CreatedAt.UTC()
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func mapDB(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return ErrUnavailable
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case "23505":
|
||||
return ErrConflict
|
||||
case "23503", "23514", "22P02":
|
||||
return ErrInvalid
|
||||
case "57014", "55P03":
|
||||
return ErrUnavailable
|
||||
}
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/internal/migrate"
|
||||
)
|
||||
|
||||
func openIntegration(t *testing.T) *PG {
|
||||
t.Helper()
|
||||
raw := os.Getenv("DATABASE_URL")
|
||||
if raw == "" {
|
||||
t.Skip("DATABASE_URL is not set")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
pg, err := Open(ctx, raw, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pg.Close)
|
||||
if err := migrate.Apply(ctx, pg.Pool()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return pg
|
||||
}
|
||||
|
||||
func TestIntegrationMigrationRerunKeepsRows(t *testing.T) {
|
||||
pg := openIntegration(t)
|
||||
ctx := context.Background()
|
||||
name := "mig_" + newID()[:8]
|
||||
if _, err := pg.CreateUser(ctx, name, "Миграция", "hash"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var before int
|
||||
if err := pg.Pool().QueryRow(ctx, `SELECT count(*) FROM users`).Scan(&before); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := migrate.Apply(ctx, pg.Pool()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var after int
|
||||
if err := pg.Pool().QueryRow(ctx, `SELECT count(*) FROM users`).Scan(&after); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if before != after {
|
||||
t.Fatalf("migration rerun changed users %d -> %d", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationUsernameRace(t *testing.T) {
|
||||
pg := openIntegration(t)
|
||||
ctx := context.Background()
|
||||
name := "race_" + newID()[:8]
|
||||
const n = 32
|
||||
var wg sync.WaitGroup
|
||||
wins := make(chan struct{}, n)
|
||||
fails := make(chan error, n)
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, err := pg.CreateUser(ctx, name, "Гонка", "hash")
|
||||
if err == nil {
|
||||
wins <- struct{}{}
|
||||
return
|
||||
}
|
||||
fails <- err
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(wins)
|
||||
close(fails)
|
||||
got := 0
|
||||
for range wins {
|
||||
got++
|
||||
}
|
||||
if got != 1 {
|
||||
t.Fatalf("winners = %d, want 1", got)
|
||||
}
|
||||
for err := range fails {
|
||||
if !errors.Is(err, ErrConflict) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationChatRollback(t *testing.T) {
|
||||
pg := openIntegration(t)
|
||||
ctx := context.Background()
|
||||
u, err := pg.CreateUser(ctx, "rb_"+newID()[:8], "Откат", "hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var before int
|
||||
if err := pg.Pool().QueryRow(ctx, `SELECT count(*) FROM chats`).Scan(&before); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = pg.CreateChat(ctx, "не должен сохраниться", []string{u.ID, "99999999-9999-4999-8999-999999999999"}, u.ID)
|
||||
if !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("want invalid, got %v", err)
|
||||
}
|
||||
var after int
|
||||
if err := pg.Pool().QueryRow(ctx, `SELECT count(*) FROM chats`).Scan(&after); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if before != after {
|
||||
t.Fatalf("rolled-back chat stayed: %d -> %d", before, after)
|
||||
}
|
||||
var members int
|
||||
if err := pg.Pool().QueryRow(ctx, `SELECT count(*) FROM chat_members WHERE user_id = $1`, u.ID).Scan(&members); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if members != 0 {
|
||||
t.Fatalf("rolled-back membership stayed: %d", members)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationIdempotencyRace(t *testing.T) {
|
||||
pg := openIntegration(t)
|
||||
ctx := context.Background()
|
||||
u, err := pg.CreateUser(ctx, "idm_"+newID()[:8], "Ключ", "hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chat, err := pg.CreateChat(ctx, "идемпотентность", []string{u.ID}, u.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const n = 16
|
||||
var wg sync.WaitGroup
|
||||
ids := make(chan string, n)
|
||||
errs := make(chan error, n)
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
msg, err := pg.AddMessage(ctx, chat.ID, u.ID, "одно", nil, "key-1", "одно")
|
||||
if err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
ids <- msg.ID
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(ids)
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seen := map[string]struct{}{}
|
||||
for id := range ids {
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
if len(seen) != 1 {
|
||||
t.Fatalf("concurrent key created %d messages", len(seen))
|
||||
}
|
||||
if _, err := pg.AddMessage(ctx, chat.ID, u.ID, "другое", nil, "key-1", "другое"); !errors.Is(err, ErrIdempotencyMismatch) {
|
||||
t.Fatalf("mismatch: %v", err)
|
||||
}
|
||||
var count int
|
||||
if err := pg.Pool().QueryRow(ctx, `SELECT count(*) FROM messages WHERE chat_id = $1`, chat.ID).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("messages = %d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresUnreachable(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
_, err := Open(ctx, "postgres://messenger:secret@127.0.0.1:1/messenger?sslmode=disable&connect_timeout=1", 1)
|
||||
if err == nil {
|
||||
t.Fatal("closed port was accepted")
|
||||
}
|
||||
}
|
||||
@@ -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