forked from mtusi2026/mtusi2026lab4
163 lines
5.0 KiB
Go
163 lines
5.0 KiB
Go
package service
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"highload/internal/repository"
|
|
"highload/internal/storage"
|
|
"io"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const attachmentReconcilePageSize = 200
|
|
const missingSampleLimit = 32
|
|
|
|
type attachmentReconcileStorage interface {
|
|
Check(context.Context) error
|
|
Head(context.Context, string) error
|
|
PutIfAbsent(context.Context, string, string, io.ReadSeeker, int64) error
|
|
}
|
|
|
|
type AttachmentReconciler struct {
|
|
repo repository.AttachmentReconcileRepository
|
|
objects attachmentReconcileStorage
|
|
options AttachmentCleanupOptions
|
|
}
|
|
|
|
type MissingReport struct {
|
|
Pages int `json:"db_pages"`
|
|
Rows int `json:"rows_scanned"`
|
|
Heads int `json:"s3_head_attempts"`
|
|
Missing int `json:"missing_objects"`
|
|
SampleIDs []string `json:"missing_attachment_ids"`
|
|
}
|
|
|
|
func NewAttachmentReconciler(repo repository.AttachmentReconcileRepository, objects attachmentReconcileStorage, options AttachmentCleanupOptions) *AttachmentReconciler {
|
|
return &AttachmentReconciler{repo: repo, objects: objects, options: options}
|
|
}
|
|
|
|
// ScanMissing checks old committed attachment rows using S3 metadata requests.
|
|
func (s *AttachmentReconciler) ScanMissing(ctx context.Context) (MissingReport, error) {
|
|
report := MissingReport{SampleIDs: []string{}}
|
|
cutoff := time.Now().Add(-s.options.GracePeriod)
|
|
if err := s.checkBucket(ctx); err != nil {
|
|
return report, err
|
|
}
|
|
var afterKey string
|
|
for {
|
|
rows, err := s.repo.ListAttachmentKeys(ctx, afterKey, attachmentReconcilePageSize)
|
|
if err != nil {
|
|
return report, err
|
|
}
|
|
report.Pages++
|
|
for _, row := range rows {
|
|
report.Rows++
|
|
if !strings.HasPrefix(row.ObjectKey, attachmentObjectPrefix) ||
|
|
row.CreatedAt.IsZero() || !row.CreatedAt.Before(cutoff) {
|
|
continue
|
|
}
|
|
report.Heads++
|
|
present, err := s.objectPresent(ctx, row.ObjectKey)
|
|
if err != nil {
|
|
return report, err
|
|
}
|
|
if !present {
|
|
report.Missing++
|
|
if len(report.SampleIDs) < missingSampleLimit {
|
|
report.SampleIDs = append(report.SampleIDs, row.ID)
|
|
}
|
|
}
|
|
}
|
|
if len(rows) < attachmentReconcilePageSize {
|
|
return report, ctx.Err()
|
|
}
|
|
afterKey = rows[len(rows)-1].ObjectKey
|
|
}
|
|
}
|
|
|
|
// Restore verifies the original bytes before writing a missing object under its existing key.
|
|
func (s *AttachmentReconciler) Restore(ctx context.Context, id string, original io.Reader) (string, error) {
|
|
attachment, err := s.repo.GetAttachmentByID(ctx, id)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if !strings.HasPrefix(attachment.ObjectKey, attachmentObjectPrefix) ||
|
|
attachment.CreatedAt.IsZero() || !attachment.CreatedAt.Before(time.Now().Add(-s.options.GracePeriod)) {
|
|
return "", errors.New("attachment is outside the restore scope or still within grace")
|
|
}
|
|
if attachment.SizeBytes <= 0 || attachment.SizeBytes > MaxAttachmentBytes {
|
|
return "", errors.New("invalid original size in attachment metadata")
|
|
}
|
|
if err := s.checkBucket(ctx); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
// Read at most one original. Keep the verified bytes stable until Put completes.
|
|
data, err := io.ReadAll(io.LimitReader(original, attachment.SizeBytes+1))
|
|
if err != nil {
|
|
return "", fmt.Errorf("read backup original: %w", err)
|
|
}
|
|
sum := sha256.Sum256(data)
|
|
if int64(len(data)) != attachment.SizeBytes || hex.EncodeToString(sum[:]) != attachment.SHA256 {
|
|
return "", errors.New("backup original does not match the stored size and SHA-256")
|
|
}
|
|
|
|
var result string
|
|
acquired, err := s.repo.WithObjectKeyLock(ctx, attachment.ObjectKey, func(txCtx context.Context, txRepo repository.AttachmentTx) error {
|
|
current, err := txRepo.GetAttachmentByID(txCtx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if current.ObjectKey != attachment.ObjectKey || current.SizeBytes != attachment.SizeBytes ||
|
|
current.SHA256 != attachment.SHA256 || current.ContentType != attachment.ContentType ||
|
|
!current.CreatedAt.Equal(attachment.CreatedAt) {
|
|
return errors.New("attachment metadata changed during restore")
|
|
}
|
|
present, err := s.objectPresent(txCtx, current.ObjectKey)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if present {
|
|
result = "already_present"
|
|
return nil
|
|
}
|
|
if s.options.DryRun {
|
|
result = "would_restore"
|
|
return nil
|
|
}
|
|
if err := s.objects.PutIfAbsent(txCtx, current.ObjectKey, current.ContentType, bytes.NewReader(data), current.SizeBytes); err != nil {
|
|
return err
|
|
}
|
|
result = "restored"
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if !acquired {
|
|
return "", errors.New("attachment key is busy; retry the restore")
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func (s *AttachmentReconciler) checkBucket(ctx context.Context) error {
|
|
ctx, cancel := context.WithTimeout(ctx, s.options.ListTimeout)
|
|
defer cancel()
|
|
return s.objects.Check(ctx)
|
|
}
|
|
|
|
func (s *AttachmentReconciler) objectPresent(ctx context.Context, key string) (bool, error) {
|
|
headCtx, cancel := context.WithTimeout(ctx, s.options.ListTimeout)
|
|
defer cancel()
|
|
err := s.objects.Head(headCtx, key)
|
|
if errors.Is(err, storage.ErrObjectNotFound) {
|
|
return false, nil
|
|
}
|
|
return err == nil, err
|
|
}
|