Переведите приём и чтение вложений на асинхронный контракт

This commit is contained in:
2026-11-18 15:33:32 +03:00
parent efc56b1382
commit bf970227d6
19 changed files with 667 additions and 367 deletions
+87 -26
View File
@@ -9,8 +9,11 @@ import (
"fmt"
"io"
"math"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
@@ -40,9 +43,10 @@ type Stats struct {
}
type Reconciler struct {
db *pgxpool.Pool
blobs Blobs
grace time.Duration
db *pgxpool.Pool
blobs Blobs
grace time.Duration
retention time.Duration
}
type ReconcileOptions struct {
@@ -51,6 +55,13 @@ type ReconcileOptions struct {
}
func NewReconciler(db *pgxpool.Pool, blobs Blobs, grace time.Duration) (*Reconciler, error) {
return NewReconcilerWithRetention(db, blobs, grace, 24*time.Hour)
}
func NewReconcilerWithRetention(db *pgxpool.Pool, blobs Blobs, grace, retention time.Duration) (*Reconciler, error) {
if retention < time.Second {
return nil, errors.New("reconcile: staging retention must be at least one second")
}
if db == nil || blobs == nil {
return nil, errors.New("reconcile: database and blobs are required")
}
@@ -60,7 +71,7 @@ func NewReconciler(db *pgxpool.Pool, blobs Blobs, grace time.Duration) (*Reconci
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
return &Reconciler{db: db, blobs: blobs, grace: grace, retention: retention}, nil
}
// Run streams findings and keeps at most one page of metadata in memory.
@@ -78,7 +89,7 @@ func (r *Reconciler) Run(ctx context.Context, options ReconcileOptions, emit fun
stats: &stats,
cutoff: started.Add(-r.grace),
}
for _, prefix := range []string{"staging/", "blobs/"} {
for _, prefix := range []string{"staging/", "variants/", "blobs/"} {
if err = run.objects(prefix); err != nil {
return stats, err
}
@@ -147,10 +158,10 @@ func (s *reconcileRun) objects(prefix string) error {
continue
}
var finding *Finding
if prefix == "staging/" {
finding, err = s.staging(obj)
} else {
if prefix == "blobs/" {
finding, err = s.orphan(obj, known[obj.Key])
} else {
finding, err = s.jobObject(prefix, obj)
}
if err != nil {
return fmt.Errorf("reconcile %s: %w", obj.Key, err)
@@ -178,26 +189,76 @@ func (s *reconcileRun) delete(key string) error {
return err
}
func (s *reconcileRun) staging(obj Object) (*Finding, error) {
f := &Finding{Kind: "stale_staging", Key: obj.Key, Action: "delete_object"}
// Failed sources remain available for operator replay until the retention period after failure elapses.
// Staging shared by several pipeline versions is retained while any active job needs it.
func (s *reconcileRun) jobObject(prefix string, obj Object) (*Finding, error) {
parts := strings.Split(strings.TrimPrefix(obj.Key, prefix), "/")
id, idErr := uuid.Parse(parts[0])
kind := "stale_staging"
query := `SELECT EXISTS(SELECT 1 FROM attachment_jobs
WHERE attachment_id=$1 AND source_key=$2 AND
(state IN ('queued','processing') OR (state='failed' AND updated_at >= now()-$3::bigint*interval '1 second')))`
args := []any{id, obj.Key, int64(s.r.retention / time.Second)}
if prefix == "variants/" {
if len(parts) != 4 || idErr != nil {
return &Finding{Kind: "invalid_variant_key", Key: obj.Key, Action: "report"}, nil
}
version, err := strconv.Atoi(parts[1])
if err != nil || version < 1 || version > math.MaxInt32 {
return &Finding{Kind: "invalid_variant_key", Key: obj.Key, Action: "report"}, nil
}
kind = "orphan_variant"
query = `SELECT EXISTS(SELECT 1 FROM attachment_variants WHERE attachment_id=$1 AND pipeline_version=$3 AND object_key=$2)
OR EXISTS(SELECT 1 FROM attachment_jobs WHERE attachment_id=$1 AND pipeline_version=$3 AND state IN ('queued','processing'))`
args[2] = version
}
finding := &Finding{Kind: kind, Key: obj.Key, Action: "delete_object"}
var keep bool
s.stats.SQLQueries++
if err := s.r.db.QueryRow(s.ctx, query, args...).Scan(&keep); err != nil {
return nil, err
}
if keep {
return nil, nil
}
if !s.apply {
return f, nil
return finding, 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
keyHash := sha256.Sum256([]byte(obj.Key))
return s.locked(keyHash[:], func(opCtx context.Context, tx pgx.Tx) (*Finding, error) {
// Intake locks the staging key before inserting an attachment. Replay,
// reprocess and completion lock the existing attachment before changing job state.
if idErr == nil {
s.stats.SQLQueries++
if _, err := tx.Exec(opCtx, `SELECT id FROM attachments WHERE id=$1 FOR UPDATE`, id); err != nil {
return nil, err
}
}
s.stats.SQLQueries++
if err := tx.QueryRow(opCtx, query, args...).Scan(&keep); err != nil {
return nil, err
}
if keep {
return nil, nil
}
op := *s
op.ctx = opCtx
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
}
finding.Applied = true
return finding, nil
})
}
func (s *reconcileRun) knownFiles(page []Object) (map[string]bool, error) {