forked from mtusi2026/mtusi2026lab4
fix: harden attachment cleanup
This commit is contained in:
@@ -161,32 +161,55 @@ func (s *Store) AttachmentReferenced(ctx context.Context, attachmentID string) (
|
||||
return referenced, nil
|
||||
}
|
||||
|
||||
func (s *Store) ClaimAttachmentForDeletion(ctx context.Context, attachmentID string, createdBefore time.Time) (bool, error) {
|
||||
func (s *Store) ClaimAttachmentForDeletion(ctx context.Context, candidate model.Attachment, createdBefore time.Time) (bool, error) {
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("begin attachment deletion claim: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
var status string
|
||||
var createdAt time.Time
|
||||
err = tx.QueryRow(ctx, `SELECT created_at FROM attachments WHERE id = $1 FOR UPDATE`, attachmentID).Scan(&createdAt)
|
||||
var readyAt *time.Time
|
||||
err = tx.QueryRow(
|
||||
ctx, `SELECT status, created_at, ready_at FROM attachments WHERE id = $1 FOR UPDATE`, candidate.ID,
|
||||
).Scan(&status, &createdAt, &readyAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("lock attachment deletion candidate: %w", err)
|
||||
}
|
||||
if createdAt.After(createdBefore) {
|
||||
if status != candidate.Status {
|
||||
return false, nil
|
||||
}
|
||||
var age time.Time
|
||||
switch status {
|
||||
case model.AttachmentPending:
|
||||
age = createdAt
|
||||
case model.AttachmentReady:
|
||||
if readyAt == nil {
|
||||
return false, nil
|
||||
}
|
||||
age = *readyAt
|
||||
default:
|
||||
return false, nil
|
||||
}
|
||||
if age.After(createdBefore) {
|
||||
return false, nil
|
||||
}
|
||||
var referenced bool
|
||||
if err := tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1)`, attachmentID).Scan(&referenced); err != nil {
|
||||
if err := tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1)`, candidate.ID).Scan(&referenced); err != nil {
|
||||
return false, fmt.Errorf("recheck attachment references: %w", err)
|
||||
}
|
||||
if referenced {
|
||||
return false, nil
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE attachments SET status = 'deleting', updated_at = clock_timestamp() WHERE id = $1`, attachmentID); err != nil {
|
||||
if _, err := tx.Exec(
|
||||
ctx,
|
||||
`UPDATE attachments SET status = 'deleting', updated_at = clock_timestamp() WHERE id = $1 AND status = $2`,
|
||||
candidate.ID, candidate.Status,
|
||||
); err != nil {
|
||||
return false, fmt.Errorf("mark attachment deleting: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user