forked from mtusi2026/mtusi2026lab4
70 lines
2.6 KiB
Go
70 lines
2.6 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
|
|
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store"
|
|
)
|
|
|
|
const attachmentColumns = `id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status,object_key,created_at,updated_at`
|
|
|
|
// Reserve creates durable intent before any S3 PUT.
|
|
func (s *Store) Reserve(ctx context.Context, a dto.Attachment) error {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
_, err := s.pool.Exec(ctx, `INSERT INTO attachments (`+attachmentColumns+`) VALUES(@id,@chat,@owner,@filename,@mime,@size,@sha,@status,@key,@created,@updated)`, pgx.StrictNamedArgs{
|
|
"id": a.ID,
|
|
"chat": a.ChatID,
|
|
"owner": a.OwnerID,
|
|
"filename": a.Filename,
|
|
"mime": a.ContentType,
|
|
"size": a.SizeBytes,
|
|
"sha": a.SHA256,
|
|
"status": a.Status,
|
|
"key": a.ObjectKey,
|
|
"created": a.CreatedAt,
|
|
"updated": a.UpdatedAt,
|
|
})
|
|
return normalize(err)
|
|
}
|
|
|
|
// Publish atomically exposes a completed object without changing its immutable key.
|
|
func (s *Store) Publish(ctx context.Context, id uuid.UUID) (dto.Attachment, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
return scanAttachment(s.pool.QueryRow(ctx, `UPDATE attachments SET status='ready',updated_at=clock_timestamp() WHERE id=@id AND status='uploading' RETURNING `+attachmentColumns, pgx.StrictNamedArgs{"id": id}))
|
|
}
|
|
|
|
// Attachment reads one immutable metadata record.
|
|
func (s *Store) Attachment(ctx context.Context, id uuid.UUID) (dto.Attachment, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
return scanAttachment(s.pool.QueryRow(ctx, `SELECT `+attachmentColumns+` FROM attachments WHERE id=@id`, pgx.StrictNamedArgs{"id": id}))
|
|
}
|
|
|
|
// scanAttachment decodes explicit columns shared by read and publication.
|
|
func scanAttachment(row pgx.Row) (dto.Attachment, error) {
|
|
var a dto.Attachment
|
|
err := row.Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.Status, &a.ObjectKey, &a.CreatedAt, &a.UpdatedAt)
|
|
return a, normalize(err)
|
|
}
|
|
|
|
// validateAttachments locks referenced metadata before inserting the message.
|
|
func validateAttachments(ctx context.Context, tx pgx.Tx, message dto.MessageDTO) error {
|
|
for _, id := range message.AttachmentIDs {
|
|
var status string
|
|
err := tx.QueryRow(ctx, `SELECT status FROM attachments WHERE id=@id AND chat_id=@chat FOR SHARE`, pgx.StrictNamedArgs{"id": id, "chat": message.ChatID}).Scan(&status)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if status != "ready" {
|
|
return store.ErrConflict
|
|
}
|
|
}
|
|
return nil
|
|
}
|