lab5: асинхронная очередь, worker и идемпотентный pipeline
API принимает 202 после durable staging и TX intent (job+outbox); отдельные relay и worker публикуют/обрабатывают задания с publisher confirm, lease, retry/backoff, DLQ и replay. Добавлены версии pipeline, варианты thumbnail/crop/optimized, presign в verified staging, status-aware sweeper и admission control.
This commit is contained in:
@@ -4,9 +4,10 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/objectstore"
|
||||
)
|
||||
@@ -16,26 +17,38 @@ type LockStore interface {
|
||||
AcquireSweepLock(ctx context.Context) (release func(), acquired bool, err error)
|
||||
}
|
||||
|
||||
// SweepRepository is the storage port used by cleanup. It exposes only
|
||||
// read/delete projections; object bytes still live in S3.
|
||||
type SweepRepository interface {
|
||||
ListPendingPresign(ctx context.Context, createdBefore time.Time, limit int) ([]domain.Attachment, error)
|
||||
DeletePending(ctx context.Context, id uuid.UUID) error
|
||||
ListStaleStaging(ctx context.Context, readyBefore, failedBefore time.Time, limit int) ([]domain.StaleStaging, error)
|
||||
MarkStagingDeleted(ctx context.Context, attachmentID uuid.UUID, stagingKey string) error
|
||||
ListReferencedKeys(ctx context.Context, afterKey string, limit int) ([]string, error)
|
||||
}
|
||||
|
||||
type SweepStats struct {
|
||||
Recovered int
|
||||
RowsDeleted int
|
||||
ObjectsDeleted int
|
||||
StagingCleared int
|
||||
}
|
||||
|
||||
type Sweeper struct {
|
||||
repo Repository
|
||||
store objectstore.Store
|
||||
locker LockStore
|
||||
grace time.Duration
|
||||
interval time.Duration
|
||||
log *slog.Logger
|
||||
repo SweepRepository
|
||||
store objectstore.Store
|
||||
locker LockStore
|
||||
grace time.Duration
|
||||
orphanGrace time.Duration
|
||||
failedRetain time.Duration
|
||||
interval time.Duration
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewSweeper(
|
||||
repo Repository,
|
||||
repo SweepRepository,
|
||||
store objectstore.Store,
|
||||
locker LockStore,
|
||||
grace, interval time.Duration,
|
||||
grace, orphanGrace, failedRetain, interval time.Duration,
|
||||
log *slog.Logger,
|
||||
) *Sweeper {
|
||||
if log == nil {
|
||||
@@ -43,12 +56,14 @@ func NewSweeper(
|
||||
}
|
||||
|
||||
return &Sweeper{
|
||||
repo: repo,
|
||||
store: store,
|
||||
locker: locker,
|
||||
grace: grace,
|
||||
interval: interval,
|
||||
log: log,
|
||||
repo: repo,
|
||||
store: store,
|
||||
locker: locker,
|
||||
grace: grace,
|
||||
orphanGrace: orphanGrace,
|
||||
failedRetain: failedRetain,
|
||||
interval: interval,
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,18 +92,18 @@ func (s *Sweeper) sweep(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if stats.Recovered+stats.RowsDeleted+stats.ObjectsDeleted > 0 {
|
||||
if stats.RowsDeleted+stats.ObjectsDeleted+stats.StagingCleared > 0 {
|
||||
s.log.InfoContext(ctx, "attachment sweep finished",
|
||||
slog.Int("recovered", stats.Recovered),
|
||||
slog.Int("rows_deleted", stats.RowsDeleted),
|
||||
slog.Int("objects_deleted", stats.ObjectsDeleted),
|
||||
slog.Int("staging_cleared", stats.StagingCleared),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// SweepOnce reconciles PostgreSQL metadata with S3 objects. It never deletes a
|
||||
// ready row or an object referenced by any row. Only objects older than the
|
||||
// grace period are candidates, so an in-flight upload cannot be collected.
|
||||
// SweepOnce applies explicit, status-aware retention rules. It never deletes
|
||||
// staging of a queued/processing attachment and aborts object collection if any
|
||||
// database page or S3 listing fails.
|
||||
func (s *Sweeper) SweepOnce(ctx context.Context) (SweepStats, error) {
|
||||
release, acquired, err := s.locker.AcquireSweepLock(ctx)
|
||||
if err != nil {
|
||||
@@ -101,72 +116,20 @@ func (s *Sweeper) SweepOnce(ctx context.Context) (SweepStats, error) {
|
||||
|
||||
defer release()
|
||||
|
||||
before := time.Now().UTC().Add(-s.grace)
|
||||
|
||||
now := time.Now().UTC()
|
||||
var stats SweepStats
|
||||
|
||||
stale, err := s.repo.ListStalePending(ctx, before, 100)
|
||||
// Abandoned presign rows: no completion ever arrived.
|
||||
pending, err := s.repo.ListPendingPresign(ctx, now.Add(-s.grace), 100)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
for _, row := range stale {
|
||||
if row.Status != domain.AttachmentPending {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.HasPrefix(row.ObjectKey, objectPrefixPresign) {
|
||||
if s.deleteObject(ctx, row.ObjectKey) {
|
||||
for _, row := range pending {
|
||||
if row.StagingKey != "" {
|
||||
if s.deleteObject(ctx, row.StagingKey) {
|
||||
stats.ObjectsDeleted++
|
||||
}
|
||||
|
||||
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
stats.RowsDeleted++
|
||||
continue
|
||||
}
|
||||
|
||||
// A proxy upload writes directly to its final key. If the process died
|
||||
// between PutObject and MarkReady, the object is complete and can be
|
||||
// recovered instead of discarded.
|
||||
head, err := s.store.Head(ctx, row.ObjectKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
stats.RowsDeleted++
|
||||
continue
|
||||
}
|
||||
|
||||
s.log.WarnContext(ctx, "sweep head failed",
|
||||
slog.String("attachment_id", row.ID.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if head.Size == row.SizeBytes && head.Metadata["sha256"] == row.SHA256 {
|
||||
if _, err := s.repo.MarkReady(ctx, row.ID, row.ObjectKey); err != nil {
|
||||
// A transient database failure must not destroy a valid object.
|
||||
// Leave both the row and the object for the next sweep.
|
||||
s.log.WarnContext(ctx, "sweep recovery failed",
|
||||
slog.String("attachment_id", row.ID.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
stats.Recovered++
|
||||
continue
|
||||
}
|
||||
|
||||
if s.deleteObject(ctx, row.ObjectKey) {
|
||||
stats.ObjectsDeleted++
|
||||
}
|
||||
|
||||
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
@@ -176,12 +139,40 @@ func (s *Sweeper) SweepOnce(ctx context.Context) (SweepStats, error) {
|
||||
stats.RowsDeleted++
|
||||
}
|
||||
|
||||
// Ready/failed rows keep their staging key until the object is safely
|
||||
// removed. Active queued/processing staging is never in this list.
|
||||
stale, err := s.repo.ListStaleStaging(
|
||||
ctx, now.Add(-s.orphanGrace), now.Add(-s.failedRetain), 100,
|
||||
)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
for _, row := range stale {
|
||||
if s.deleteObject(ctx, row.StagingKey) {
|
||||
stats.ObjectsDeleted++
|
||||
}
|
||||
|
||||
if err := s.repo.MarkStagingDeleted(ctx, row.AttachmentID, row.StagingKey); err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
stats.StagingCleared++
|
||||
}
|
||||
|
||||
referenced, err := s.referencedKeys(ctx)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
for _, prefix := range []string{objectPrefixAttachments, objectPrefixStaging} {
|
||||
// Orphans: objects no row references. Final objects and variants use the
|
||||
// normal grace; staging uses the longer orphan grace.
|
||||
for _, prefix := range []string{domain.AttachmentsPrefix, "staging/"} {
|
||||
before := now.Add(-s.grace)
|
||||
if prefix == "staging/" {
|
||||
before = now.Add(-s.orphanGrace)
|
||||
}
|
||||
|
||||
objects, err := s.store.List(ctx, prefix)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
@@ -209,20 +200,23 @@ func (s *Sweeper) referencedKeys(ctx context.Context) (map[string]struct{}, erro
|
||||
const pageSize = 1000
|
||||
|
||||
keys := make(map[string]struct{})
|
||||
after := ""
|
||||
|
||||
for offset := int32(0); ; offset += pageSize {
|
||||
rows, err := s.repo.ListKeys(ctx, pageSize, offset)
|
||||
for {
|
||||
rows, err := s.repo.ListReferencedKeys(ctx, after, pageSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, row := range rows {
|
||||
keys[row.ObjectKey] = struct{}{}
|
||||
for _, key := range rows {
|
||||
keys[key] = struct{}{}
|
||||
}
|
||||
|
||||
if len(rows) < pageSize {
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
after = rows[len(rows)-1]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user