217 lines
5.6 KiB
Go
217 lines
5.6 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"log"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"high-loud-apps-labs/internal/domain"
|
|
)
|
|
|
|
const advisoryLockKey int64 = 0x4D5455534904
|
|
|
|
type Reconciler struct {
|
|
attachments domain.AttachmentRepository
|
|
storage domain.ObjectStorage
|
|
outbox domain.OutboxRepository
|
|
pool *pgxpool.Pool
|
|
gracePeriod time.Duration
|
|
batchSize int
|
|
}
|
|
|
|
func NewReconciler(
|
|
attachments domain.AttachmentRepository,
|
|
storage domain.ObjectStorage,
|
|
outbox domain.OutboxRepository,
|
|
pool *pgxpool.Pool,
|
|
gracePeriod time.Duration,
|
|
) *Reconciler {
|
|
if gracePeriod <= 0 {
|
|
gracePeriod = time.Hour
|
|
}
|
|
return &Reconciler{
|
|
attachments: attachments,
|
|
storage: storage,
|
|
outbox: outbox,
|
|
pool: pool,
|
|
gracePeriod: gracePeriod,
|
|
batchSize: 100,
|
|
}
|
|
}
|
|
|
|
func (r *Reconciler) Run(ctx context.Context, interval time.Duration) {
|
|
if interval <= 0 {
|
|
interval = 5 * time.Minute
|
|
}
|
|
ticker := time.NewTicker(interval)
|
|
defer ticker.Stop()
|
|
|
|
log.Printf("reconciler: запущен (interval=%s, grace=%s)", interval, r.gracePeriod)
|
|
r.tick(ctx)
|
|
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
log.Println("reconciler: остановлен")
|
|
return
|
|
case <-ticker.C:
|
|
r.tick(ctx)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (r *Reconciler) tick(ctx context.Context) {
|
|
acquired, release, err := r.acquireLock(ctx)
|
|
if err != nil {
|
|
log.Printf("reconciler: ошибка получения блокировки: %v", err)
|
|
return
|
|
}
|
|
if !acquired {
|
|
return
|
|
}
|
|
defer release()
|
|
|
|
leasesReset := r.sweepExpiredLeases(ctx)
|
|
stagingDeleted := r.sweepStaging(ctx)
|
|
orphansDeleted := r.sweepOrphans(ctx)
|
|
|
|
if leasesReset > 0 || stagingDeleted > 0 || orphansDeleted > 0 {
|
|
log.Printf("reconciler: очистка завершена (восстановлено_задач=%d, удалено_staging=%d, удалено_сирот=%d)", leasesReset, stagingDeleted, orphansDeleted)
|
|
}
|
|
}
|
|
|
|
func (r *Reconciler) acquireLock(ctx context.Context) (bool, func(), error) {
|
|
conn, err := r.pool.Acquire(ctx)
|
|
if err != nil {
|
|
return false, nil, err
|
|
}
|
|
|
|
var ok bool
|
|
if err := conn.QueryRow(ctx, `SELECT pg_try_advisory_lock($1)`, advisoryLockKey).Scan(&ok); err != nil {
|
|
conn.Release()
|
|
return false, nil, err
|
|
}
|
|
if !ok {
|
|
conn.Release()
|
|
return false, nil, nil
|
|
}
|
|
|
|
release := func() {
|
|
unlockCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
if _, err := conn.Exec(unlockCtx, `SELECT pg_advisory_unlock($1)`, advisoryLockKey); err != nil {
|
|
log.Printf("reconciler: ошибка снятия блокировки: %v", err)
|
|
}
|
|
conn.Release()
|
|
}
|
|
return true, release, nil
|
|
}
|
|
|
|
func (r *Reconciler) sweepExpiredLeases(ctx context.Context) int {
|
|
expired, err := r.attachments.ListExpiredLeases(ctx, r.batchSize)
|
|
if err != nil {
|
|
log.Printf("reconciler: ошибка получения истёкших аренд: %v", err)
|
|
return 0
|
|
}
|
|
|
|
recovered := 0
|
|
for _, a := range expired {
|
|
if err := r.attachments.ResetLease(ctx, a.ID); err != nil {
|
|
log.Printf("reconciler: ошибка сброса аренды для %s: %v", a.ID, err)
|
|
continue
|
|
}
|
|
|
|
payload, _ := json.Marshal(domain.JobMessage{
|
|
AttachmentID: a.ID,
|
|
PipelineVersion: a.PipelineVersion,
|
|
Attempt: a.Attempts + 1,
|
|
})
|
|
err := r.outbox.EnqueueDirect(ctx, &domain.OutboxEntry{
|
|
AggregateType: domain.OutboxAggregateAttachment,
|
|
AggregateID: a.ID,
|
|
EventType: domain.OutboxEventProcess,
|
|
Payload: payload,
|
|
CreatedAt: time.Now().UTC(),
|
|
})
|
|
if err != nil {
|
|
log.Printf("reconciler: ошибка постановки в очередь восстановленной задачи %s: %v", a.ID, err)
|
|
continue
|
|
}
|
|
recovered++
|
|
}
|
|
return recovered
|
|
}
|
|
|
|
// Чистим staging в S3 для готовых задач
|
|
func (r *Reconciler) sweepStaging(ctx context.Context) int {
|
|
toCleanup, err := r.attachments.ListStagingToCleanup(ctx, r.batchSize)
|
|
if err != nil {
|
|
log.Printf("reconciler: ошибка получения списка staging для очистки: %v", err)
|
|
return 0
|
|
}
|
|
|
|
deleted := 0
|
|
for _, a := range toCleanup {
|
|
if err := r.storage.Delete(ctx, a.StagingKey); err != nil {
|
|
log.Printf("reconciler: ошибка удаления объекта staging %s: %v", a.StagingKey, err)
|
|
continue
|
|
}
|
|
if err := r.attachments.ClearStagingKey(ctx, a.ID); err != nil {
|
|
log.Printf("reconciler: ошибка очистки ключа staging %s: %v", a.ID, err)
|
|
continue
|
|
}
|
|
deleted++
|
|
}
|
|
return deleted
|
|
}
|
|
|
|
// Удаляем старые сиротские объекты (без записи в БД)
|
|
func (r *Reconciler) sweepOrphans(ctx context.Context) int {
|
|
objects, err := r.storage.List(ctx, "chats/")
|
|
if err != nil {
|
|
log.Printf("reconciler: ошибка получения списка объектов: %v", err)
|
|
return 0
|
|
}
|
|
if len(objects) == 0 {
|
|
return 0
|
|
}
|
|
|
|
cutoff := time.Now().UTC().Add(-r.gracePeriod)
|
|
keys := make([]string, 0, len(objects))
|
|
for _, o := range objects {
|
|
if o.LastModified.Before(cutoff) {
|
|
keys = append(keys, o.Key)
|
|
}
|
|
}
|
|
if len(keys) == 0 {
|
|
return 0
|
|
}
|
|
|
|
existing, err := r.attachments.ExistingKeys(ctx, keys)
|
|
if err != nil {
|
|
log.Printf("reconciler: ошибка получения существующих ключей: %v", err)
|
|
return 0
|
|
}
|
|
|
|
inDB := make(map[string]struct{}, len(existing))
|
|
for _, k := range existing {
|
|
inDB[k] = struct{}{}
|
|
}
|
|
|
|
deleted := 0
|
|
for _, k := range keys {
|
|
if _, ok := inDB[k]; ok {
|
|
continue
|
|
}
|
|
if err := r.storage.Delete(ctx, k); err != nil {
|
|
log.Printf("reconciler: ошибка удаления сиротского объекта %s: %v", k, err)
|
|
continue
|
|
}
|
|
deleted++
|
|
}
|
|
return deleted
|
|
}
|