Добавьте S3-вложения с дедупликацией и безопасной сверкой хранилищ
This commit is contained in:
@@ -0,0 +1,479 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
const (
|
||||
reconcilePageSize = 500
|
||||
reconcileOperationTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
type Finding struct {
|
||||
Kind string `json:"kind"`
|
||||
Key string `json:"key"`
|
||||
Action string `json:"action"`
|
||||
Applied bool `json:"applied"`
|
||||
}
|
||||
|
||||
// SQLQueries counts SQL statements, including transaction control and locks.
|
||||
// S3Calls counts calls to the Blobs port, including each list page and deep GET.
|
||||
type Stats struct {
|
||||
ElapsedMS int64 `json:"elapsed_ms"`
|
||||
SQLQueries int64 `json:"sql_queries"`
|
||||
S3Calls int64 `json:"s3_calls"`
|
||||
ScannedFiles int64 `json:"scanned_files"`
|
||||
ScannedObjects int64 `json:"scanned_objects"`
|
||||
Findings int64 `json:"findings"`
|
||||
Repaired int64 `json:"repaired"`
|
||||
}
|
||||
|
||||
type Reconciler struct {
|
||||
db *pgxpool.Pool
|
||||
blobs Blobs
|
||||
grace time.Duration
|
||||
}
|
||||
|
||||
func NewReconciler(db *pgxpool.Pool, blobs Blobs, grace time.Duration) (*Reconciler, error) {
|
||||
if db == nil || blobs == nil {
|
||||
return nil, errors.New("reconcile: database and blobs are required")
|
||||
}
|
||||
if grace == 0 {
|
||||
grace = time.Hour
|
||||
}
|
||||
if grace < 2*time.Minute {
|
||||
return nil, errors.New("reconcile: grace must be at least two minutes")
|
||||
}
|
||||
return &Reconciler{db: db, blobs: blobs, grace: grace}, nil
|
||||
}
|
||||
|
||||
// Run streams findings and keeps at most one page of metadata in memory.
|
||||
// Dry runs only read storage. Each apply candidate is checked again under the
|
||||
// publisher's transaction lock; no scan snapshot authorizes a later mutation.
|
||||
func (r *Reconciler) Run(ctx context.Context, apply, deep bool, emit func(Finding)) (stats Stats, err error) {
|
||||
started := time.Now()
|
||||
defer func() { stats.ElapsedMS = time.Since(started).Milliseconds() }()
|
||||
run := reconcileRun{r: r, ctx: ctx, apply: apply, deep: deep, emit: emit, stats: &stats, cutoff: started.Add(-r.grace)}
|
||||
for _, prefix := range []string{"staging/", "blobs/"} {
|
||||
if err = run.objects(prefix); err != nil {
|
||||
return stats, err
|
||||
}
|
||||
}
|
||||
err = run.files()
|
||||
return stats, err
|
||||
}
|
||||
|
||||
type reconcileRun struct {
|
||||
r *Reconciler
|
||||
ctx context.Context
|
||||
apply, deep bool
|
||||
emit func(Finding)
|
||||
stats *Stats
|
||||
cutoff time.Time
|
||||
}
|
||||
|
||||
func (s *reconcileRun) note(f *Finding) {
|
||||
if f == nil {
|
||||
return
|
||||
}
|
||||
s.stats.Findings++
|
||||
if f.Applied {
|
||||
s.stats.Repaired++
|
||||
}
|
||||
if s.emit != nil {
|
||||
s.emit(*f)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *reconcileRun) old(modified time.Time) bool {
|
||||
// Unknown timestamps must never authorize collection.
|
||||
return !modified.IsZero() && modified.Before(s.cutoff)
|
||||
}
|
||||
|
||||
func (s *reconcileRun) objects(prefix string) error {
|
||||
after := ""
|
||||
for {
|
||||
if err := s.ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
s.stats.S3Calls++
|
||||
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
|
||||
page, err := s.r.blobs.List(opCtx, prefix, after, reconcilePageSize)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return fmt.Errorf("reconcile list %s: %w", prefix, err)
|
||||
}
|
||||
if len(page) == 0 {
|
||||
return nil
|
||||
}
|
||||
var known map[string]bool
|
||||
if prefix == "blobs/" {
|
||||
known, err = s.knownFiles(page)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, obj := range page {
|
||||
if obj.Key <= after {
|
||||
return errors.New("reconcile: object page did not advance")
|
||||
}
|
||||
after = obj.Key
|
||||
s.stats.ScannedObjects++
|
||||
if !s.old(obj.Modified) {
|
||||
continue
|
||||
}
|
||||
var finding *Finding
|
||||
if prefix == "staging/" {
|
||||
finding, err = s.staging(obj)
|
||||
} else {
|
||||
finding, err = s.orphan(obj, known[obj.Key])
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("reconcile %s: %w", obj.Key, err)
|
||||
}
|
||||
s.note(finding)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *reconcileRun) stat(key string) (Object, error) {
|
||||
s.stats.S3Calls++
|
||||
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
|
||||
defer cancel()
|
||||
return s.r.blobs.Stat(opCtx, key)
|
||||
}
|
||||
|
||||
func (s *reconcileRun) delete(key string) error {
|
||||
s.stats.S3Calls++
|
||||
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
|
||||
defer cancel()
|
||||
err := s.r.blobs.Delete(opCtx, key)
|
||||
if errors.Is(err, ErrObjectMissing) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *reconcileRun) staging(obj Object) (*Finding, error) {
|
||||
f := &Finding{Kind: "stale_staging", Key: obj.Key, Action: "delete_object"}
|
||||
if !s.apply {
|
||||
return f, nil
|
||||
}
|
||||
current, err := s.stat(obj.Key)
|
||||
if errors.Is(err, ErrObjectMissing) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !s.old(current.Modified) {
|
||||
return nil, nil
|
||||
}
|
||||
if err = s.delete(obj.Key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.Applied = true
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func (s *reconcileRun) knownFiles(page []Object) (map[string]bool, error) {
|
||||
hashes := make([][]byte, 0, len(page))
|
||||
for _, obj := range page {
|
||||
if !s.old(obj.Modified) {
|
||||
continue
|
||||
}
|
||||
hash, err := hex.DecodeString(obj.Key[len("blobs/"):])
|
||||
if err == nil && len(hash) == sha256.Size && BlobKey(hash) == obj.Key {
|
||||
hashes = append(hashes, hash)
|
||||
}
|
||||
}
|
||||
known := make(map[string]bool, len(hashes))
|
||||
if len(hashes) == 0 {
|
||||
return known, nil
|
||||
}
|
||||
s.stats.SQLQueries++
|
||||
rows, err := s.r.db.Query(s.ctx, `SELECT hash FROM files WHERE hash=ANY($1::bytea[])`, hashes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var hash []byte
|
||||
if err := rows.Scan(&hash); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
known[BlobKey(hash)] = true
|
||||
}
|
||||
return known, rows.Err()
|
||||
}
|
||||
|
||||
func (s *reconcileRun) orphan(obj Object, known bool) (*Finding, error) {
|
||||
hash, err := hex.DecodeString(obj.Key[len("blobs/"):])
|
||||
if err != nil || len(hash) != sha256.Size || BlobKey(hash) != obj.Key {
|
||||
return &Finding{Kind: "invalid_blob_key", Key: obj.Key, Action: "report"}, nil
|
||||
}
|
||||
if known {
|
||||
return nil, nil
|
||||
}
|
||||
f := &Finding{Kind: "orphan_blob", Key: obj.Key, Action: "delete_object"}
|
||||
if !s.apply {
|
||||
return f, nil
|
||||
}
|
||||
return s.locked(hash, func(opCtx context.Context, tx pgx.Tx) (*Finding, error) {
|
||||
op := *s
|
||||
op.ctx = opCtx
|
||||
var exists bool
|
||||
s.stats.SQLQueries++
|
||||
if err := tx.QueryRow(opCtx, `SELECT EXISTS(SELECT 1 FROM files WHERE hash=$1)`, hash).Scan(&exists); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if exists {
|
||||
return nil, nil
|
||||
}
|
||||
current, err := op.stat(obj.Key)
|
||||
if errors.Is(err, ErrObjectMissing) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !s.old(current.Modified) {
|
||||
return nil, nil
|
||||
}
|
||||
if err = op.delete(obj.Key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.Applied = true
|
||||
return f, nil
|
||||
})
|
||||
}
|
||||
|
||||
// locked also covers hashes without a files row: a publisher and an orphan
|
||||
// collector therefore cannot pass each other's existence check concurrently.
|
||||
func (s *reconcileRun) locked(hash []byte, fn func(context.Context, pgx.Tx) (*Finding, error)) (*Finding, error) {
|
||||
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
|
||||
defer cancel()
|
||||
s.stats.SQLQueries++
|
||||
tx, err := s.r.db.Begin(opCtx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
committed := false
|
||||
defer func() {
|
||||
if !committed {
|
||||
cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
s.stats.SQLQueries++
|
||||
_ = tx.Rollback(cleanup)
|
||||
}
|
||||
}()
|
||||
// Pool defaults cover ordinary requests; object I/O can outlive those
|
||||
// idle limits. The operation deadline bounds the entire locked candidate.
|
||||
s.stats.SQLQueries++
|
||||
if _, err = tx.Exec(opCtx, `SET LOCAL idle_in_transaction_session_timeout='35s'`); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.stats.SQLQueries++
|
||||
if err = LockHash(opCtx, tx, hash); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f, err := fn(opCtx, tx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.stats.SQLQueries++
|
||||
err = tx.Commit(opCtx)
|
||||
committed = true // pgx closes the transaction even when COMMIT fails.
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
type reconcileFile struct {
|
||||
hash []byte
|
||||
size int64
|
||||
status string
|
||||
created time.Time
|
||||
referenced bool
|
||||
}
|
||||
|
||||
func (s *reconcileRun) files() error {
|
||||
after := []byte{}
|
||||
for {
|
||||
if err := s.ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
s.stats.SQLQueries++
|
||||
rows, err := s.r.db.Query(s.ctx, `SELECT f.hash,f.size_bytes,f.status,f.created_at,
|
||||
EXISTS(SELECT 1 FROM attachments a WHERE a.file_hash=f.hash)
|
||||
FROM files f WHERE f.hash>$1 ORDER BY f.hash LIMIT 500`, after)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
page := make([]reconcileFile, 0, reconcilePageSize)
|
||||
for rows.Next() {
|
||||
var f reconcileFile
|
||||
if err = rows.Scan(&f.hash, &f.size, &f.status, &f.created, &f.referenced); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
page = append(page, f)
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(page) == 0 {
|
||||
return nil
|
||||
}
|
||||
// Close the page's SQL rows before acquiring a transaction connection.
|
||||
for _, f := range page {
|
||||
after = f.hash
|
||||
s.stats.ScannedFiles++
|
||||
if !s.candidate(f) {
|
||||
continue
|
||||
}
|
||||
var finding *Finding
|
||||
if s.apply {
|
||||
finding, err = s.locked(f.hash, func(opCtx context.Context, tx pgx.Tx) (*Finding, error) {
|
||||
op := *s
|
||||
op.ctx = opCtx
|
||||
var current reconcileFile
|
||||
s.stats.SQLQueries++
|
||||
err := tx.QueryRow(opCtx, `SELECT f.hash,f.size_bytes,f.status,f.created_at,
|
||||
EXISTS(SELECT 1 FROM attachments a WHERE a.file_hash=f.hash)
|
||||
FROM files f WHERE f.hash=$1 FOR UPDATE OF f`, f.hash).
|
||||
Scan(¤t.hash, ¤t.size, ¤t.status, ¤t.created, ¤t.referenced)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !s.candidate(current) {
|
||||
return nil, nil
|
||||
}
|
||||
return op.inspect(current, tx)
|
||||
})
|
||||
} else {
|
||||
finding, err = s.inspect(f, nil)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("reconcile file %s: %w", BlobKey(f.hash), err)
|
||||
}
|
||||
s.note(finding)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *reconcileRun) candidate(f reconcileFile) bool {
|
||||
if !s.old(f.created) {
|
||||
return false
|
||||
}
|
||||
if !f.referenced {
|
||||
return f.status == "pending" || f.status == "ready"
|
||||
}
|
||||
return f.status == "ready" || f.status == "failed"
|
||||
}
|
||||
|
||||
func (s *reconcileRun) inspect(f reconcileFile, tx pgx.Tx) (*Finding, error) {
|
||||
key := BlobKey(f.hash)
|
||||
if !f.referenced {
|
||||
// A publication that rolled back can leave fresh bytes behind an old
|
||||
// pending row. Both the metadata and the current object must be old.
|
||||
obj, err := s.stat(key)
|
||||
if err != nil && !errors.Is(err, ErrObjectMissing) {
|
||||
return nil, err
|
||||
}
|
||||
if err == nil && !s.old(obj.Modified) {
|
||||
return nil, nil
|
||||
}
|
||||
finding := &Finding{Kind: "unreferenced_" + f.status, Key: key, Action: "delete_file"}
|
||||
if !s.apply {
|
||||
return finding, nil
|
||||
}
|
||||
// S3 must succeed first. A failed SQL commit then leaves a missing,
|
||||
// unreferenced row that the next run can safely finish collecting.
|
||||
if err := s.delete(key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.stats.SQLQueries++
|
||||
if _, err := tx.Exec(s.ctx, `DELETE FROM files WHERE hash=$1`, f.hash); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
finding.Applied = true
|
||||
return finding, nil
|
||||
}
|
||||
obj, err := s.stat(key)
|
||||
if errors.Is(err, ErrObjectMissing) {
|
||||
if f.status == "failed" {
|
||||
return nil, nil
|
||||
}
|
||||
finding := &Finding{Kind: "missing_blob", Key: key, Action: "mark_failed"}
|
||||
if s.apply {
|
||||
s.stats.SQLQueries++
|
||||
if _, err = tx.Exec(s.ctx, `UPDATE files SET status='failed' WHERE hash=$1`, f.hash); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
finding.Applied = true
|
||||
}
|
||||
return finding, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if obj.Size != f.size {
|
||||
return &Finding{Kind: "size_mismatch", Key: key, Action: "report"}, nil
|
||||
}
|
||||
if s.deep {
|
||||
match, err := s.verify(f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !match {
|
||||
return &Finding{Kind: "hash_mismatch", Key: key, Action: "report"}, nil
|
||||
}
|
||||
}
|
||||
// A failed file stays failed even when the key reappears. Recovery requires
|
||||
// an explicit publisher; a shallow HEAD cannot prove content integrity.
|
||||
if f.status == "failed" {
|
||||
return &Finding{Kind: "failed_present", Key: key, Action: "report"}, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *reconcileRun) verify(f reconcileFile) (bool, error) {
|
||||
if f.size < 0 || f.size == math.MaxInt64 {
|
||||
return false, errors.New("reconcile: invalid file size")
|
||||
}
|
||||
s.stats.S3Calls++
|
||||
opCtx, cancel := context.WithTimeout(s.ctx, reconcileOperationTimeout)
|
||||
defer cancel()
|
||||
body, err := s.r.blobs.Open(opCtx, BlobKey(f.hash))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
hash := sha256.New()
|
||||
n, readErr := io.Copy(hash, io.LimitReader(body, f.size+1))
|
||||
closeErr := body.Close()
|
||||
if readErr != nil {
|
||||
return false, readErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return false, closeErr
|
||||
}
|
||||
return n == f.size && bytes.Equal(hash.Sum(nil), f.hash), nil
|
||||
}
|
||||
Reference in New Issue
Block a user