Files
mtusi2026lab6/service/internal/adapter/repository/storage/attachments.go
T
2026-11-17 13:08:13 +03:00

66 lines
2.5 KiB
Go

package storage
import (
"context"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"encoding/json"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
)
type AttachmentRecord = dto.AttachmentRecord
type AttachmentsRepo struct{ Pool *pgxpool.Pool }
const AttachmentColumns = "id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at,object_key,integrity_missing,status,error_code,pipeline_version,staging_key,variants,variant_keys"
func ScanAttachment(row pgx.Row) (*AttachmentRecord, error) {
a := new(AttachmentRecord)
p := &a.Public
var variants, keys []byte
if err := row.Scan(&p.Id, &p.ChatId, &p.OwnerId, &p.Filename, &p.ContentType, &p.SizeBytes, &p.Sha256, &p.CreatedAt, &p.UpdatedAt, &a.Key, &a.Missing, &p.Status, &p.ErrorCode, &a.PipelineVersion, &a.StagingKey, &variants, &keys); err != nil {
return nil, apperr.WrapPostgres(err, "attachment unavailable")
}
if err := json.Unmarshal(variants, &p.Variants); err != nil {
return nil, err
}
if err := json.Unmarshal(keys, &a.VariantKeys); err != nil {
return nil, err
}
return a, nil
}
func (r *AttachmentsRepo) Get(ctx context.Context, id uuid.UUID) (*AttachmentRecord, error) {
return ScanAttachment(r.Pool.QueryRow(ctx, "SELECT "+AttachmentColumns+" FROM attachments WHERE id=$1", id))
}
// Session locks span S3 work and the database commit. A lost connection releases
// the lock; the mandatory grace period also exceeds the maximum upload lifetime.
func (r *AttachmentsRepo) Lock(ctx context.Context, key string) (*pgxpool.Conn, func(), error) {
c, e := r.Pool.Acquire(ctx)
if e != nil {
return nil, nil, apperr.WrapPostgres(e, "database unavailable")
}
if _, e = c.Exec(ctx, "SELECT pg_advisory_lock(hashtextextended($1, 42))", key); e != nil {
// The server may have acquired the session lock before cancellation was
// observed by the client. Never return that uncertain session to the pool.
clean, cancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = c.Conn().Close(clean)
cancel()
c.Release()
return nil, nil, apperr.WrapPostgres(e, "lock unavailable")
}
return c, func() {
// Close rather than return a possibly locked session when unlock fails.
clean, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if _, e := c.Exec(clean, "SELECT pg_advisory_unlock(hashtextextended($1, 42))", key); e != nil {
_ = c.Conn().Close(clean)
}
c.Release()
}, nil
}