forked from mtusi2026/mtusi2026lab6
442 lines
12 KiB
Go
442 lines
12 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"highload/internal/database/sqlc"
|
|
"highload/internal/model"
|
|
"highload/internal/repository"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
const attachmentTransactionTimeout = 5 * time.Second
|
|
|
|
type AttachmentRepository struct {
|
|
queries *sqlc.Queries
|
|
pool *pgxpool.Pool
|
|
maxAttempts int32
|
|
}
|
|
|
|
func NewAttachmentRepository(queries *sqlc.Queries, pool *pgxpool.Pool, attemptLimit ...int32) *AttachmentRepository {
|
|
maxAttempts := int32(5)
|
|
if len(attemptLimit) > 0 {
|
|
maxAttempts = attemptLimit[0]
|
|
}
|
|
return &AttachmentRepository{
|
|
queries: queries,
|
|
pool: pool,
|
|
maxAttempts: maxAttempts,
|
|
}
|
|
}
|
|
|
|
func (r *AttachmentRepository) CreateAttachment(ctx context.Context, params repository.CreateAttachmentParams) (*model.Attachment, error) {
|
|
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
|
defer cancel()
|
|
chatUUID, err := getUUIDFromString(params.ChatID)
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
ownerUUID, err := getUUIDFromString(params.OwnerID)
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
|
|
sqlcParams := sqlc.CreateAttachmentParams{
|
|
ChatID: *chatUUID,
|
|
OwnerID: *ownerUUID,
|
|
Filename: params.Filename,
|
|
ObjectKey: params.ObjectKey,
|
|
ContentType: params.ContentType,
|
|
SizeBytes: params.SizeBytes,
|
|
Sha256: params.Sha256,
|
|
}
|
|
|
|
sqlcAttachment, err := r.queries.CreateAttachment(dbCtx, sqlcParams)
|
|
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
|
|
attachment := mapAttachmentSqlcToModel(sqlc.Attachment(sqlcAttachment))
|
|
return attachment, nil
|
|
|
|
}
|
|
|
|
func (r *AttachmentRepository) GetAttachmentForUser(ctx context.Context, userID, attachmentID string) (*model.Attachment, error) {
|
|
userUUID, err := getUUIDFromString(userID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
attachmentUUID, err := getUUIDFromString(attachmentID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
txCtx, cancel := context.WithTimeout(ctx, time.Second)
|
|
defer cancel()
|
|
|
|
params := sqlc.GetAttachmentForUserParams{
|
|
AttachmentID: *attachmentUUID,
|
|
UserID: *userUUID,
|
|
}
|
|
|
|
tx, err := r.pool.BeginTx(txCtx, pgx.TxOptions{
|
|
IsoLevel: pgx.RepeatableRead,
|
|
AccessMode: pgx.ReadOnly,
|
|
})
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
defer rollbackTx(ctx, tx)
|
|
|
|
txQueries := r.queries.WithTx(tx)
|
|
|
|
sqlcAttachment, err := txQueries.GetAttachmentForUser(txCtx, params)
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
attachment := mapAttachmentSqlcToModel(sqlcAttachment)
|
|
|
|
if sqlcAttachment.Status == "ready" {
|
|
variants, err := txQueries.ListAttachmentVariants(txCtx, sqlc.ListAttachmentVariantsParams{
|
|
AttachmentID: sqlcAttachment.ID,
|
|
PipelineVersion: sqlcAttachment.PipelineVersion,
|
|
})
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
|
|
for _, v := range variants {
|
|
attachment.Variants = append(attachment.Variants, model.AttachmentVariant{
|
|
Name: v.Name,
|
|
ObjectKey: v.ObjectKey,
|
|
ContentType: v.ContentType,
|
|
SizeBytes: v.SizeBytes,
|
|
Width: int(v.Width),
|
|
Height: int(v.Height),
|
|
SHA256: v.Sha256,
|
|
})
|
|
}
|
|
}
|
|
|
|
if err = tx.Commit(txCtx); err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
|
|
return attachment, nil
|
|
|
|
}
|
|
|
|
func (r *AttachmentRepository) ExistsByObjectKey(ctx context.Context, key string) (bool, error) {
|
|
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
|
defer cancel()
|
|
|
|
exists, err := r.queries.AttachmentExistsByObjectKey(dbCtx, key)
|
|
if err != nil {
|
|
return false, convertDBError(err)
|
|
}
|
|
return exists, nil
|
|
}
|
|
|
|
func (r *AttachmentRepository) ListAttachmentKeys(ctx context.Context, afterKey string, pageSize int32) ([]repository.AttachmentKey, error) {
|
|
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
|
defer cancel()
|
|
|
|
rows, err := r.queries.ListAttachmentKeys(dbCtx, sqlc.ListAttachmentKeysParams{
|
|
AfterKey: pgtype.Text{String: afterKey, Valid: true},
|
|
PageSize: pageSize,
|
|
})
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
keys := make([]repository.AttachmentKey, 0, len(rows))
|
|
for _, row := range rows {
|
|
keys = append(keys, repository.AttachmentKey{
|
|
ID: row.ID.String(), ObjectKey: row.ObjectKey.String, CreatedAt: row.CreatedAt.Time,
|
|
})
|
|
}
|
|
return keys, nil
|
|
}
|
|
|
|
func (r *AttachmentRepository) GetAttachmentByID(ctx context.Context, id string) (*model.Attachment, error) {
|
|
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
|
defer cancel()
|
|
|
|
attachmentID, err := getUUIDFromString(id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
row, err := r.queries.GetAttachmentByID(dbCtx, *attachmentID)
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
return mapAttachmentSqlcToModel(row), nil
|
|
}
|
|
|
|
func (r *AttachmentRepository) WithObjectKeyLock(ctx context.Context, key string, fn func(context.Context, repository.AttachmentTx) error) (bool, error) {
|
|
txCtx, cancel := context.WithTimeout(ctx, attachmentTransactionTimeout)
|
|
defer cancel()
|
|
|
|
tx, err := r.pool.BeginTx(txCtx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
|
|
if err != nil {
|
|
return false, convertDBError(err)
|
|
}
|
|
|
|
defer rollbackTx(ctx, tx)
|
|
|
|
txQueries := r.queries.WithTx(tx)
|
|
|
|
locked, err := txQueries.TryLockAttachmentObjectKey(txCtx, key)
|
|
|
|
if err != nil {
|
|
return false, convertDBError(err)
|
|
}
|
|
|
|
if !locked {
|
|
return false, nil
|
|
}
|
|
|
|
txRepo := &AttachmentRepository{queries: txQueries, maxAttempts: r.maxAttempts}
|
|
|
|
if err = fn(txCtx, txRepo); err != nil {
|
|
return true, err
|
|
}
|
|
|
|
if err = tx.Commit(txCtx); err != nil {
|
|
return true, convertDBError(err)
|
|
}
|
|
|
|
return true, nil
|
|
}
|
|
|
|
func (r *AttachmentRepository) CreateQueued(ctx context.Context, queuedID, chatID, ownerID, mime, sha256, key, filename string, size int64) (*model.Attachment, error) {
|
|
queuedUUID, err := getUUIDFromString(queuedID)
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
|
|
chatUUID, err := getUUIDFromString(chatID)
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
ownerUUID, err := getUUIDFromString(ownerID)
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
|
|
cqaParams := sqlc.CreateQueuedAttachmentParams{
|
|
ID: *queuedUUID,
|
|
ChatID: *chatUUID,
|
|
OwnerID: *ownerUUID,
|
|
Filename: filename,
|
|
ContentType: mime,
|
|
SizeBytes: size,
|
|
Sha256: sha256,
|
|
StagingKey: pgtype.Text{String: key, Valid: true},
|
|
}
|
|
|
|
// The upload path already holds the object lock in a transaction.
|
|
if r.pool == nil {
|
|
return r.insertQueued(ctx, r.queries, cqaParams)
|
|
}
|
|
|
|
txCtx, cancel := context.WithTimeout(ctx, attachmentTransactionTimeout)
|
|
defer cancel()
|
|
tx, err := r.pool.BeginTx(txCtx, pgx.TxOptions{})
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
defer rollbackTx(ctx, tx)
|
|
queued, err := r.insertQueued(txCtx, r.queries.WithTx(tx), cqaParams)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := tx.Commit(txCtx); err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
return queued, nil
|
|
}
|
|
|
|
func (r *AttachmentRepository) insertQueued(txCtx context.Context, txQueries *sqlc.Queries, cqaParams sqlc.CreateQueuedAttachmentParams) (*model.Attachment, error) {
|
|
|
|
sqlcAttachment, err := txQueries.CreateQueuedAttachment(txCtx, cqaParams)
|
|
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
|
|
if _, err := r.createPipelineJob(txCtx, txQueries, sqlcAttachment); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return mapAttachmentSqlcToModel(sqlcAttachment), nil
|
|
|
|
}
|
|
|
|
func (r *AttachmentRepository) ClaimJob(ctx context.Context, jobID string, leaseUntil time.Time) (*model.AttachmentJob, error) {
|
|
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
|
defer cancel()
|
|
|
|
jobUUID, err := getUUIDFromString(jobID)
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
|
|
arg := sqlc.ClaimJobParams{
|
|
NewLeaseUntil: pgtype.Timestamptz{Time: leaseUntil, Valid: true},
|
|
JobID: *jobUUID,
|
|
}
|
|
|
|
row, err := r.queries.ClaimJob(dbCtx, arg)
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
return nil, convertDBError(err)
|
|
}
|
|
|
|
return &model.AttachmentJob{
|
|
ID: row.ID.String(),
|
|
AttachmentID: row.AttachmentID.String(),
|
|
PipelineVersion: row.PipelineVersion,
|
|
AttemptsStarted: row.AttemptsStarted,
|
|
MaxAttempts: row.MaxAttempts,
|
|
LeaseGeneration: row.LeaseGeneration,
|
|
LeaseUntil: row.LeaseUntil.Time,
|
|
AcceptedAt: row.CreatedAt.Time,
|
|
}, nil
|
|
}
|
|
|
|
func (r *AttachmentRepository) GetAttachmentJobState(ctx context.Context, jobID string) (*model.AttachmentJobState, error) {
|
|
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
|
defer cancel()
|
|
|
|
jobUUID, err := getUUIDFromString(jobID)
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
|
|
row, err := r.queries.GetAttachmentJobState(dbCtx, *jobUUID)
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
|
|
state := &model.AttachmentJobState{
|
|
AttachmentID: row.AttachmentID.String(),
|
|
PipelineVersion: row.PipelineVersion,
|
|
ID: row.ID.String(),
|
|
Status: row.Status,
|
|
LeaseGeneration: row.LeaseGeneration,
|
|
AttemptsStarted: row.AttemptsStarted,
|
|
MaxAttempts: row.MaxAttempts,
|
|
LeaseExpired: row.LeaseExpired,
|
|
}
|
|
|
|
if row.LeaseUntil.Valid {
|
|
state.LeaseUntil = &row.LeaseUntil.Time
|
|
}
|
|
if row.NextAttemptAt.Valid {
|
|
state.NextAttemptAt = &row.NextAttemptAt.Time
|
|
}
|
|
|
|
return state, nil
|
|
|
|
}
|
|
|
|
func (r *AttachmentRepository) CompleteJob(
|
|
ctx context.Context, jobID string, leaseGeneration int32,
|
|
originalKey string, variants []model.AttachmentVariant,
|
|
) (bool, error) {
|
|
jobUUID, err := getUUIDFromString(jobID)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
txCtx, cancel := context.WithTimeout(ctx, attachmentTransactionTimeout)
|
|
defer cancel()
|
|
tx, err := r.pool.BeginTx(txCtx, pgx.TxOptions{})
|
|
if err != nil {
|
|
return false, convertDBError(err)
|
|
}
|
|
defer rollbackTx(ctx, tx)
|
|
txQueries := r.queries.WithTx(tx)
|
|
lockedJob, err := txQueries.LockActiveAttachmentJob(txCtx, sqlc.LockActiveAttachmentJobParams{
|
|
JobID: *jobUUID,
|
|
LeaseGeneration: leaseGeneration,
|
|
})
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return false, nil
|
|
}
|
|
if err != nil {
|
|
return false, convertDBError(err)
|
|
}
|
|
|
|
const maxDimension = 1<<31 - 1
|
|
for _, variant := range variants {
|
|
if variant.Width <= 0 || variant.Width > maxDimension ||
|
|
variant.Height <= 0 || variant.Height > maxDimension {
|
|
return false, repository.ErrInvalidInput
|
|
}
|
|
err := txQueries.CreateAttachmentVariant(txCtx, sqlc.CreateAttachmentVariantParams{
|
|
AttachmentID: lockedJob.AttachmentID,
|
|
PipelineVersion: lockedJob.PipelineVersion,
|
|
Name: variant.Name,
|
|
ObjectKey: variant.ObjectKey,
|
|
ContentType: variant.ContentType,
|
|
SizeBytes: variant.SizeBytes,
|
|
Width: int32(variant.Width),
|
|
Height: int32(variant.Height),
|
|
Sha256: variant.SHA256,
|
|
})
|
|
if err != nil {
|
|
return false, convertDBError(err)
|
|
}
|
|
}
|
|
|
|
rows, err := txQueries.CompleteJob(txCtx, sqlc.CompleteJobParams{
|
|
JobID: *jobUUID,
|
|
LeaseGeneration: leaseGeneration,
|
|
ObjectKey: originalKey,
|
|
})
|
|
if err != nil {
|
|
return false, convertDBError(err)
|
|
}
|
|
if rows == 0 {
|
|
return false, nil
|
|
}
|
|
if err := tx.Commit(txCtx); err != nil {
|
|
return false, convertDBError(err)
|
|
}
|
|
return true, nil
|
|
|
|
}
|
|
|
|
func mapAttachmentSqlcToModel(sa sqlc.Attachment) *model.Attachment {
|
|
var errorCode *string
|
|
if sa.ErrorCode.Valid {
|
|
errorCode = &sa.ErrorCode.String
|
|
}
|
|
return &model.Attachment{
|
|
Variants: []model.AttachmentVariant{},
|
|
ErrorCode: errorCode,
|
|
StagingKey: sa.StagingKey.String,
|
|
ID: sa.ID.String(),
|
|
ChatID: sa.ChatID.String(),
|
|
OwnerID: sa.OwnerID.String(),
|
|
Filename: sa.Filename,
|
|
ObjectKey: sa.ObjectKey.String,
|
|
ContentType: sa.ContentType,
|
|
SizeBytes: sa.SizeBytes,
|
|
Status: sa.Status,
|
|
PipelineVersion: sa.PipelineVersion,
|
|
SHA256: sa.Sha256,
|
|
CreatedAt: sa.CreatedAt.Time,
|
|
UpdatedAt: sa.UpdatedAt.Time,
|
|
}
|
|
|
|
}
|