forked from mtusi2026/mtusi2026lab4
287 lines
7.5 KiB
Go
287 lines
7.5 KiB
Go
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
|
|
}
|