forked from mtusi2026/mtusi2026lab5
ЛР 5 — асинхронная обработка и версии pipeline
This commit is contained in:
@@ -0,0 +1,440 @@
|
||||
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,
|
||||
}, 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,
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type ChatRepository struct {
|
||||
queries *sqlc.Queries
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatRepository(queries *sqlc.Queries, pool *pgxpool.Pool) *ChatRepository {
|
||||
return &ChatRepository{
|
||||
queries: queries,
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ChatRepository) CreateChat(ctx context.Context, title string, memberIDs []string) (*model.Chat, error) {
|
||||
txCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
tx, err := r.pool.Begin(txCtx)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
rollbackCtx, rollbackCancel := context.WithTimeout(
|
||||
context.WithoutCancel(ctx),
|
||||
time.Second,
|
||||
)
|
||||
defer rollbackCancel()
|
||||
|
||||
_ = tx.Rollback(rollbackCtx)
|
||||
}()
|
||||
txQueries := r.queries.WithTx(tx)
|
||||
|
||||
sqlcChat, err := txQueries.CreateChat(txCtx, title)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
chat := &model.Chat{
|
||||
ID: sqlcChat.ID.String(),
|
||||
Title: sqlcChat.Title,
|
||||
CreatedAt: sqlcChat.CreatedAt.Time,
|
||||
}
|
||||
|
||||
for _, id := range memberIDs {
|
||||
userID, err := getUUIDFromString(id)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
err = txQueries.CreateChatMember(txCtx, sqlc.CreateChatMemberParams{ChatID: sqlcChat.ID, UserID: *userID})
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
}
|
||||
|
||||
chat.MemberIDs = slices.Clone(memberIDs)
|
||||
|
||||
err = tx.Commit(txCtx)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetChatByID(ctx context.Context, id string) (*model.Chat, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
uuidID, err := getUUIDFromString(id)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
sqlcChat, err := r.queries.GetChatByID(dbCtx, *uuidID)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
chat := mapChatSqlcToModel(&sqlcChat)
|
||||
|
||||
return chat, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetChatsByUserID(ctx context.Context, userID string, limit int, after *repository.ChatPosition) ([]*model.Chat, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
uuidUserID, err := getUUIDFromString(userID)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
afterCreatedAt := pgtype.Timestamptz{Valid: false}
|
||||
afterID := pgtype.UUID{Valid: false}
|
||||
|
||||
if after != nil {
|
||||
afterCreatedAt = pgtype.Timestamptz{Time: after.CreatedAt, Valid: true}
|
||||
if uuidFromString, err := getUUIDFromString(after.ID); err == nil {
|
||||
afterID = *uuidFromString
|
||||
} else {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
}
|
||||
|
||||
chats, err := r.queries.GetChatsByUserID(dbCtx, sqlc.GetChatsByUserIDParams{UserID: *uuidUserID, AfterCreatedAt: afterCreatedAt, AfterID: afterID, LimitCount: int32(limit)})
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
resultChats := make([]*model.Chat, len(chats))
|
||||
for index, sqlcChat := range chats {
|
||||
memberIDs := make([]string, len(sqlcChat.MemberIds))
|
||||
|
||||
for i, memberID := range sqlcChat.MemberIds {
|
||||
memberIDs[i] = memberID.String()
|
||||
}
|
||||
|
||||
resultChats[index] = &model.Chat{
|
||||
ID: sqlcChat.ID.String(),
|
||||
MemberIDs: memberIDs,
|
||||
CreatedAt: sqlcChat.CreatedAt.Time,
|
||||
Title: sqlcChat.Title,
|
||||
}
|
||||
}
|
||||
|
||||
return resultChats, nil
|
||||
}
|
||||
|
||||
func mapChatSqlcToModel(sqlcChat *sqlc.GetChatByIDRow) *model.Chat {
|
||||
|
||||
memberIDs := make([]string, len(sqlcChat.MemberIds))
|
||||
|
||||
for i, memberID := range sqlcChat.MemberIds {
|
||||
memberIDs[i] = memberID.String()
|
||||
}
|
||||
|
||||
return &model.Chat{
|
||||
ID: sqlcChat.ID.String(),
|
||||
MemberIDs: memberIDs,
|
||||
CreatedAt: sqlcChat.CreatedAt.Time,
|
||||
Title: sqlcChat.Title,
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"highload/internal/repository"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func convertDBError(err error) error {
|
||||
var pgErr *pgconn.PgError
|
||||
var netErr *net.OpError
|
||||
var dnsErr *net.DNSError
|
||||
|
||||
switch {
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
return fmt.Errorf("%w: %v", repository.ErrServiceUnavailable, err)
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
return repository.ErrNotFound
|
||||
case errors.As(err, &pgErr):
|
||||
switch pgErr.Code {
|
||||
case "23505":
|
||||
return repository.ErrAlreadyExists
|
||||
case "53300", "57P03", "08006", "08001", "57P01", "57P02":
|
||||
return repository.ErrServiceUnavailable
|
||||
}
|
||||
case errors.Is(err, io.EOF) ||
|
||||
errors.Is(err, io.ErrUnexpectedEOF) ||
|
||||
errors.Is(err, pgconn.ErrConnClosed):
|
||||
return repository.ErrServiceUnavailable
|
||||
case errors.Is(err, repository.ErrInvalidInput):
|
||||
return repository.ErrInvalidInput
|
||||
case errors.As(err, &netErr):
|
||||
return repository.ErrServiceUnavailable
|
||||
case errors.As(err, &dnsErr):
|
||||
return repository.ErrServiceUnavailable
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: %v", repository.ErrDatabase, err)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type MessageRepository struct {
|
||||
queries *sqlc.Queries
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessageRepository(queries *sqlc.Queries, pool *pgxpool.Pool) *MessageRepository {
|
||||
return &MessageRepository{
|
||||
queries: queries,
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *MessageRepository) CreateMessage(ctx context.Context, chatID, senderID, text, key string, attachmentIDs []string) (*model.Message, error) {
|
||||
chat, err := getUUIDFromString(chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sender, err := getUUIDFromString(senderID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ids := make([]pgtype.UUID, 0, len(attachmentIDs))
|
||||
canonical := make([]string, 0, len(attachmentIDs))
|
||||
for _, attachmentID := range attachmentIDs {
|
||||
id, err := getUUIDFromString(attachmentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, *id)
|
||||
canonical = append(canonical, id.String())
|
||||
}
|
||||
|
||||
txCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
tx, err := r.pool.Begin(txCtx)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
defer rollbackTx(ctx, tx)
|
||||
q := r.queries.WithTx(tx)
|
||||
|
||||
if err := q.LockMessageRequest(txCtx, sqlc.LockMessageRequestParams{UserID: *sender, ChatID: *chat, IdempotencyKey: key}); err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
if err := q.DeleteExpiredMessageIdempotency(txCtx, sqlc.DeleteExpiredMessageIdempotencyParams{UserID: *sender, ChatID: *chat, IdempotencyKey: key}); err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
message, err := q.GetIdempotentMessage(txCtx, sqlc.GetIdempotentMessageParams{UserID: *sender, ChatID: *chat, IdempotencyKey: key})
|
||||
switch {
|
||||
case err == nil:
|
||||
rows, err := q.GetMessagesAttachments(txCtx, message.ID)
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
saved := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
saved = append(saved, row.AttachmentID.String())
|
||||
}
|
||||
if message.Text != text || !slices.Equal(saved, canonical) {
|
||||
return nil, repository.ErrConflict
|
||||
}
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
if len(ids) > 0 {
|
||||
rows, err := q.LockAttachmentsForMessage(txCtx, sqlc.LockAttachmentsForMessageParams{ChatID: *chat, AttachmentIds: ids})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
if len(rows) != len(ids) {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
for _, row := range rows {
|
||||
if row.Status == "failed" {
|
||||
return nil, repository.ErrConflict
|
||||
}
|
||||
}
|
||||
}
|
||||
message, err = q.CreateMessage(txCtx, sqlc.CreateMessageParams{ChatID: *chat, SenderID: *sender, Text: text})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
for i, id := range ids {
|
||||
n, err := q.CreateMessagesAttachments(txCtx, sqlc.CreateMessagesAttachmentsParams{
|
||||
MessageID: message.ID, AttachmentID: id, ChatID: *chat, Position: int16(i),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
if n != 1 {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
}
|
||||
n, err := q.InsertMessageIdempotency(txCtx, sqlc.InsertMessageIdempotencyParams{
|
||||
UserID: *sender, ChatID: *chat, IdempotencyKey: key, MessageID: message.ID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
if n != 1 {
|
||||
return nil, repository.ErrConflict
|
||||
}
|
||||
default:
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
if err := tx.Commit(txCtx); err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
return &model.Message{
|
||||
ID: message.ID.String(), ChatID: message.ChatID.String(), SenderID: message.SenderID.String(),
|
||||
Text: message.Text, CreatedAt: message.CreatedAt.Time, AttachmentIDs: canonical,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) GetMessagesByChatID(ctx context.Context, chatID string, limit int, after *repository.MessagePosition) ([]*model.Message, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
uuidChatID, err := getUUIDFromString(chatID)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
afterCreatedAt := pgtype.Timestamptz{Valid: false}
|
||||
afterID := pgtype.UUID{Valid: false}
|
||||
|
||||
if after != nil {
|
||||
afterCreatedAt = pgtype.Timestamptz{Time: after.CreatedAt, Valid: true}
|
||||
if uuidFromString, err := getUUIDFromString(after.ID); err == nil {
|
||||
afterID = *uuidFromString
|
||||
} else {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
}
|
||||
|
||||
sqlcMessages, err := r.queries.GetMessagesByChatID(dbCtx, sqlc.GetMessagesByChatIDParams{ChatID: *uuidChatID, AfterID: afterID, AfterCreatedAt: afterCreatedAt, LimitCount: int32(limit)})
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
messageIDs := make([]pgtype.UUID, len(sqlcMessages))
|
||||
for index, _ := range sqlcMessages {
|
||||
messageIDs[index] = sqlcMessages[index].ID
|
||||
}
|
||||
|
||||
messageRow, err := r.queries.GetAttachmentsForMessages(dbCtx, messageIDs)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
mapMessagesAtt := make(map[string][]string)
|
||||
for index, _ := range messageRow {
|
||||
messageID := messageRow[index].MessageID.String()
|
||||
attachmentID := messageRow[index].AttachmentID.String()
|
||||
|
||||
mapMessagesAtt[messageID] = append(mapMessagesAtt[messageID], attachmentID)
|
||||
|
||||
}
|
||||
|
||||
messages := make([]*model.Message, len(sqlcMessages))
|
||||
|
||||
for index, sqlcMessage := range sqlcMessages {
|
||||
messages[index] = &model.Message{
|
||||
ID: sqlcMessage.ID.String(),
|
||||
ChatID: sqlcMessage.ChatID.String(),
|
||||
SenderID: sqlcMessage.SenderID.String(),
|
||||
Text: sqlcMessage.Text,
|
||||
AttachmentIDs: mapMessagesAtt[sqlcMessage.ID.String()],
|
||||
CreatedAt: sqlcMessage.CreatedAt.Time}
|
||||
}
|
||||
|
||||
return messages, nil
|
||||
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/repository"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
func (r *AttachmentRepository) ScheduleRetry(ctx context.Context, jobID string, generation int32, code string, at time.Time) (bool, error) {
|
||||
id, err := getUUIDFromString(jobID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := r.queries.ScheduleRetry(ctx, sqlc.ScheduleRetryParams{
|
||||
JobID: *id, LeaseGeneration: generation, ErrorCode: code,
|
||||
AvailableAt: pgtype.Timestamptz{Time: at, Valid: true},
|
||||
})
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
return n == 1, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) FailJob(ctx context.Context, jobID string, generation int32, code string) (bool, error) {
|
||||
id, err := getUUIDFromString(jobID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := r.queries.FailJob(ctx, sqlc.FailJobParams{
|
||||
JobID: *id, LeaseGeneration: generation, ErrorCode: code,
|
||||
})
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
return n == 1, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) EnqueueExpiredLeases(ctx context.Context, batchSize int32) (int, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
rows, err := r.queries.EnqueueExpiredLeases(ctx, batchSize)
|
||||
if err != nil {
|
||||
return 0, convertDBError(err)
|
||||
}
|
||||
return len(rows), nil
|
||||
}
|
||||
|
||||
// PublishPending holds the outbox row until the broker confirms delivery.
|
||||
func (r *AttachmentRepository) PublishPending(ctx context.Context, publish func(context.Context, sqlc.Outbox) error) (bool, error) {
|
||||
txCtx, cancel := context.WithTimeout(ctx, 8*time.Second)
|
||||
defer cancel()
|
||||
tx, err := r.pool.Begin(txCtx)
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
defer rollbackTx(ctx, tx)
|
||||
q := r.queries.WithTx(tx)
|
||||
row, err := q.NextPendingOutboxEvent(txCtx)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
if err := publish(txCtx, row); err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, err := q.MarkOutboxEventSent(txCtx, row.ID)
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
if n != 1 {
|
||||
return false, fmt.Errorf("outbox row disappeared during publish")
|
||||
}
|
||||
if err := tx.Commit(txCtx); err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) ListFailedJobs(ctx context.Context) ([]sqlc.ListFailedAttachmentJobsRow, error) {
|
||||
return r.queries.ListFailedAttachmentJobs(ctx, 100)
|
||||
}
|
||||
|
||||
// ReplayFailed checks the staged object while holding the same job lock as cleanup.
|
||||
func (r *AttachmentRepository) ReplayFailed(ctx context.Context, jobID, requestID, operator, reason string, extra int32, check func(context.Context, string) error) (bool, error) {
|
||||
id, err := getUUIDFromString(jobID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
request, err := getUUIDFromString(requestID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
txCtx, cancel := context.WithTimeout(ctx, attachmentTransactionTimeout)
|
||||
defer cancel()
|
||||
tx, err := r.pool.Begin(txCtx)
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
defer rollbackTx(ctx, tx)
|
||||
q := r.queries.WithTx(tx)
|
||||
job, err := q.LockAttachmentJobForReplay(txCtx, *id)
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
att, err := q.GetAttachmentByID(txCtx, job.AttachmentID)
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
if att.Status != "failed" || att.PipelineVersion != job.PipelineVersion {
|
||||
return false, nil
|
||||
}
|
||||
if !att.StagingKey.Valid {
|
||||
return false, fmt.Errorf("staging has expired: %w", repository.ErrNotFound)
|
||||
}
|
||||
if err := check(txCtx, att.StagingKey.String); err != nil {
|
||||
return false, err
|
||||
}
|
||||
rows, err := q.ReplayFailed(txCtx, sqlc.ReplayFailedParams{
|
||||
JobID: *id, RequestID: *request, OperatorID: operator, Reason: reason, ExtraAttempts: extra,
|
||||
})
|
||||
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 (r *AttachmentRepository) PublishedObjectKeys(ctx context.Context, attachmentID string, version int32) ([]string, error) {
|
||||
id, err := getUUIDFromString(attachmentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
original, err := r.queries.GetPublishedOriginalKey(ctx, sqlc.GetPublishedOriginalKeyParams{
|
||||
AttachmentID: *id, PipelineVersion: version,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
variants, err := r.queries.ListAttachmentVariants(ctx, sqlc.ListAttachmentVariantsParams{
|
||||
AttachmentID: *id, PipelineVersion: version,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
keys := []string{original.String}
|
||||
for _, v := range variants {
|
||||
keys = append(keys, v.ObjectKey)
|
||||
}
|
||||
if len(keys) != 4 {
|
||||
return nil, fmt.Errorf("ready job has an incomplete variant set")
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/storage"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type CleanupPolicy struct {
|
||||
Now time.Time
|
||||
Grace time.Duration
|
||||
Retention time.Duration
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// CleanupObject synchronizes with upload, finalization and operator replay.
|
||||
// All candidate metadata is rechecked while holding the relevant lock.
|
||||
func (r *AttachmentRepository) CleanupObject(ctx context.Context, obj storage.ObjectInfo, policy CleanupPolicy, deleteObject func(context.Context, string) error) (bool, error) {
|
||||
txCtx, cancel := context.WithTimeout(ctx, attachmentTransactionTimeout)
|
||||
defer cancel()
|
||||
tx, err := r.pool.Begin(txCtx)
|
||||
if err != nil {
|
||||
return false, convertDBError(err)
|
||||
}
|
||||
defer rollbackTx(ctx, tx)
|
||||
q := r.queries.WithTx(tx)
|
||||
locked, err := q.TryLockAttachmentObjectKey(txCtx, obj.Key)
|
||||
if err != nil || !locked {
|
||||
return false, err
|
||||
}
|
||||
|
||||
staging, err := q.GetAttachmentByStagingKey(txCtx, obj.Key)
|
||||
keepObject := false
|
||||
switch {
|
||||
case err == nil:
|
||||
version := staging.PipelineVersion
|
||||
_, err = q.LockAttachmentJobForPipeline(txCtx, sqlc.LockAttachmentJobForPipelineParams{
|
||||
AttachmentID: staging.ID, PipelineVersion: staging.PipelineVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
staging, err = q.GetAttachmentByID(txCtx, staging.ID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if staging.PipelineVersion != version || staging.StagingKey.String != obj.Key ||
|
||||
(staging.Status == "ready" && staging.ObjectKey.String == obj.Key) {
|
||||
return false, nil
|
||||
}
|
||||
if staging.Status != "ready" && (staging.Status != "failed" || staging.UpdatedAt.Time.Add(policy.Retention).After(policy.Now)) {
|
||||
return false, nil
|
||||
}
|
||||
// An upgrade can stage the original published by the previous version.
|
||||
keepObject, err = q.IsPublishedOriginalKey(txCtx, obj.Key)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
return false, err
|
||||
default:
|
||||
if obj.LastModified.IsZero() || obj.LastModified.Add(policy.Grace).After(policy.Now) {
|
||||
return false, nil
|
||||
}
|
||||
if strings.HasPrefix(obj.Key, "results/") {
|
||||
// Keys include the job version and the generating lease.
|
||||
parts := strings.Split(obj.Key, "/")
|
||||
if len(parts) != 5 {
|
||||
return false, nil
|
||||
}
|
||||
id, idErr := getUUIDFromString(parts[1])
|
||||
version, versionErr := strconv.ParseInt(strings.TrimPrefix(parts[2], "v"), 10, 32)
|
||||
generation, generationErr := strconv.ParseInt(parts[3], 10, 32)
|
||||
if idErr != nil || versionErr != nil || generationErr != nil || version < 1 || generation < 1 {
|
||||
return false, nil
|
||||
}
|
||||
job, err := q.LockAttachmentJobForPipeline(txCtx, sqlc.LockAttachmentJobForPipelineParams{
|
||||
AttachmentID: *id, PipelineVersion: int32(version),
|
||||
})
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, err
|
||||
}
|
||||
if err == nil && job.LeaseGeneration == int32(generation) && job.LeaseUntil.Valid {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
exists, err := q.AttachmentExistsByObjectKey(txCtx, obj.Key)
|
||||
if err != nil || exists {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
if policy.DryRun {
|
||||
return true, nil
|
||||
}
|
||||
if !keepObject {
|
||||
if err := deleteObject(txCtx, obj.Key); err != nil && !errors.Is(err, storage.ErrObjectNotFound) {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
if staging.StagingKey.Valid {
|
||||
if _, err = q.ClearStagingReference(txCtx, sqlc.ClearStagingReferenceParams{
|
||||
ID: staging.ID, StagingKey: staging.StagingKey,
|
||||
}); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(txCtx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return !keepObject, nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
"time"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func NewUserRepository(queries *sqlc.Queries) *UserRepository {
|
||||
return &UserRepository{queries: queries}
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(ctx context.Context, username, displayName string, passwordHash string) (*model.User, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
sqlcUser, err := r.queries.CreateUser(dbCtx, sqlc.CreateUserParams{Username: username, DisplayName: displayName, PasswordHash: passwordHash})
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
user := &model.User{
|
||||
ID: sqlcUser.ID.String(),
|
||||
Username: sqlcUser.Username,
|
||||
DisplayName: sqlcUser.DisplayName,
|
||||
CreatedAt: sqlcUser.CreatedAt.Time,
|
||||
PasswordHash: sqlcUser.PasswordHash,
|
||||
}
|
||||
|
||||
return user, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetUserByID(ctx context.Context, id string) (*model.User, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
uuidID, err := getUUIDFromString(id)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
sqlcUser, err := r.queries.GetUserByID(dbCtx, *uuidID)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
user := &model.User{
|
||||
ID: sqlcUser.ID.String(),
|
||||
Username: sqlcUser.Username,
|
||||
DisplayName: sqlcUser.DisplayName,
|
||||
CreatedAt: sqlcUser.CreatedAt.Time,
|
||||
PasswordHash: sqlcUser.PasswordHash,
|
||||
}
|
||||
|
||||
return user, nil
|
||||
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetUserByUsername(ctx context.Context, username string) (*model.User, error) {
|
||||
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
|
||||
sqlcUser, err := r.queries.GetUserByUsername(dbCtx, username)
|
||||
|
||||
if err != nil {
|
||||
return nil, convertDBError(err)
|
||||
}
|
||||
|
||||
user := &model.User{
|
||||
ID: sqlcUser.ID.String(),
|
||||
Username: sqlcUser.Username,
|
||||
DisplayName: sqlcUser.DisplayName,
|
||||
CreatedAt: sqlcUser.CreatedAt.Time,
|
||||
PasswordHash: sqlcUser.PasswordHash,
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"highload/internal/repository"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
func getUUIDFromString(id string) (*pgtype.UUID, error) {
|
||||
var uuidID pgtype.UUID
|
||||
|
||||
if err := uuidID.Scan(id); err != nil {
|
||||
return nil, repository.ErrInvalidInput
|
||||
}
|
||||
|
||||
return &uuidID, nil
|
||||
}
|
||||
|
||||
func rollbackTx(ctx context.Context, tx pgx.Tx) {
|
||||
rollbackCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second)
|
||||
defer cancel()
|
||||
_ = tx.Rollback(rollbackCtx)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/repository"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
func (r *AttachmentRepository) createPipelineJob(ctx context.Context, q *sqlc.Queries, att sqlc.Attachment) (pgtype.UUID, error) {
|
||||
job, err := q.CreateAttachmentJob(ctx, sqlc.CreateAttachmentJobParams{
|
||||
AttachmentID: att.ID, PipelineVersion: att.PipelineVersion,
|
||||
AvailableAt: att.UpdatedAt, MaxAttempts: r.maxAttempts,
|
||||
})
|
||||
if err != nil {
|
||||
return pgtype.UUID{}, convertDBError(err)
|
||||
}
|
||||
if err := q.CreateInitialOutboxEvent(ctx, job.ID); err != nil {
|
||||
return pgtype.UUID{}, convertDBError(err)
|
||||
}
|
||||
return job.ID, nil
|
||||
}
|
||||
|
||||
// UpgradePipeline serializes the version switch with version 1's finalization,
|
||||
// retries and staging cleanup on its job row. The version 2 job starts fresh.
|
||||
func (r *AttachmentRepository) UpgradePipeline(ctx context.Context, attachmentID string, checkSource func(context.Context, string) error) (string, bool, error) {
|
||||
id, err := getUUIDFromString(attachmentID)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
txCtx, cancel := context.WithTimeout(ctx, attachmentTransactionTimeout)
|
||||
defer cancel()
|
||||
tx, err := r.pool.Begin(txCtx)
|
||||
if err != nil {
|
||||
return "", false, convertDBError(err)
|
||||
}
|
||||
defer rollbackTx(ctx, tx)
|
||||
q := r.queries.WithTx(tx)
|
||||
oldJob, err := q.LockAttachmentJobForPipeline(txCtx, sqlc.LockAttachmentJobForPipelineParams{
|
||||
AttachmentID: *id, PipelineVersion: 1,
|
||||
})
|
||||
if err != nil {
|
||||
return "", false, convertDBError(err)
|
||||
}
|
||||
att, err := q.GetAttachmentByID(txCtx, *id)
|
||||
if err != nil {
|
||||
return "", false, convertDBError(err)
|
||||
}
|
||||
if att.PipelineVersion == 2 {
|
||||
jobID, err := q.GetPipelineJobID(txCtx, sqlc.GetPipelineJobIDParams{AttachmentID: *id, PipelineVersion: 2})
|
||||
if err != nil {
|
||||
return "", false, convertDBError(err)
|
||||
}
|
||||
return jobID.String(), false, nil
|
||||
}
|
||||
if att.PipelineVersion != 1 {
|
||||
return "", false, fmt.Errorf("cannot upgrade pipeline version %d", att.PipelineVersion)
|
||||
}
|
||||
source := att.StagingKey
|
||||
if att.Status == "ready" {
|
||||
source = att.ObjectKey
|
||||
}
|
||||
if !source.Valid {
|
||||
return "", false, fmt.Errorf("original has expired: %w", repository.ErrNotFound)
|
||||
}
|
||||
if err := checkSource(txCtx, source.String); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if err := q.SupersedeAttachmentJob(txCtx, oldJob.ID); err != nil {
|
||||
return "", false, convertDBError(err)
|
||||
}
|
||||
upgraded, err := q.QueueAttachmentUpgrade(txCtx, sqlc.QueueAttachmentUpgradeParams{ID: *id, SourceKey: source.String})
|
||||
if err != nil {
|
||||
return "", false, convertDBError(err)
|
||||
}
|
||||
jobID, err := r.createPipelineJob(txCtx, q, upgraded)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if err := tx.Commit(txCtx); err != nil {
|
||||
return "", false, convertDBError(err)
|
||||
}
|
||||
return jobID.String(), true, nil
|
||||
}
|
||||
Reference in New Issue
Block a user