package com.example.mtusi_messenger.service; import com.example.mtusi_messenger.repository.AttachmentRepository; import com.example.mtusi_messenger.storage.ObjectStorage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.HashSet; import java.util.Set; @Component @ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true) public class AttachmentReconciler { private static final Logger log = LoggerFactory.getLogger(AttachmentReconciler.class); private static final String PREFIX = "attachments/"; private final AttachmentRepository attachments; private final ObjectStorage storage; private final Duration gracePeriod; private final boolean dryRun; private final Clock clock; @Autowired public AttachmentReconciler( AttachmentRepository attachments, ObjectStorage storage, @Value("${messenger.attachments.cleanup-grace-seconds:3600}") long graceSeconds, @Value("${messenger.attachments.cleanup-dry-run:false}") boolean dryRun ) { this(attachments, storage, Duration.ofSeconds(graceSeconds), dryRun, Clock.systemUTC()); } AttachmentReconciler(AttachmentRepository attachments, ObjectStorage storage, Duration gracePeriod, boolean dryRun, Clock clock) { if (gracePeriod.isNegative() || gracePeriod.isZero()) { throw new IllegalArgumentException("Attachment cleanup grace period must be positive"); } this.attachments = attachments; this.storage = storage; this.gracePeriod = gracePeriod; this.dryRun = dryRun; this.clock = clock; } @Scheduled( fixedDelayString = "${messenger.attachments.reconcile-interval-millis:600000}", initialDelayString = "${messenger.attachments.reconcile-initial-delay-millis:60000}") public void scheduledReconcile() { try { Report report = reconcile(); if (report.orphanObjects() > 0 || report.missingObjects() > 0) { log.warn("Attachment reconciliation: {} orphan, {} deleted, {} missing, dryRun={}", report.orphanObjects(), report.deletedObjects(), report.missingObjects(), dryRun); } } catch (RuntimeException error) { log.warn("Attachment reconciliation postponed: {}", error.getMessage()); } } public Report reconcile() { Set databaseKeys = attachments.findAllObjectKeys(); var storedObjects = storage.list(PREFIX); Set storageKeys = new HashSet<>(); Instant deleteBefore = clock.instant().minus(gracePeriod); int orphans = 0; int deleted = 0; for (ObjectStorage.StoredObject object : storedObjects) { storageKeys.add(object.objectKey()); if (!databaseKeys.contains(object.objectKey()) && object.lastModified().isBefore(deleteBefore)) { orphans++; if (!dryRun) { storage.delete(object.objectKey()); deleted++; } } } int missing = 0; for (String databaseKey : databaseKeys) { if (!storageKeys.contains(databaseKey)) { missing++; log.error("Attachment metadata references missing object {}", databaseKey); } } return new Report(databaseKeys.size(), storedObjects.size(), orphans, deleted, missing, dryRun); } public record Report(int metadataObjects, int storageObjects, int orphanObjects, int deletedObjects, int missingObjects, boolean dryRun) { } }