Files
mtusi2026lab5/java/src/main/java/com/vnp/demo/service/AttachmentPersistenceService.java
T
2026-11-10 17:12:13 +03:00

94 lines
2.3 KiB
Java

package com.vnp.demo.service;
import java.nio.file.Path;
import java.time.Instant;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import com.vnp.demo.models.Attachment;
import com.vnp.demo.repositories.AttachmentRepository;
@Service
public class AttachmentPersistenceService {
private final AttachmentRepository attachmentRepository;
private final S3StorageService storage;
public AttachmentPersistenceService(
AttachmentRepository attachmentRepository,
S3StorageService storage
) {
this.attachmentRepository = attachmentRepository;
this.storage = storage;
}
@Transactional(
isolation = Isolation.READ_COMMITTED,
timeout = 60
)
public void save(
Attachment attachment,
Path temporaryFile
) {
attachmentRepository.lockObject(
attachment.objectKey()
);
storage.put(
attachment.objectKey(),
temporaryFile,
attachment.sizeBytes(),
attachment.contentType()
);
attachmentRepository.save(attachment);
}
@Transactional(
isolation = Isolation.READ_COMMITTED,
timeout = 30
)
public CleanupResult removeIfOrphan(
String objectKey,
Instant cutoff
) {
if (!objectKey.startsWith("originals/")) {
return CleanupResult.SKIPPED;
}
if (!attachmentRepository.tryLockObject(objectKey)) {
return CleanupResult.BUSY;
}
if (attachmentRepository.existsByObjectKey(objectKey)) {
return CleanupResult.REFERENCED;
}
Instant lastModified = storage.lastModifiedOrNull(
objectKey
);
if (lastModified == null) {
return CleanupResult.MISSING;
}
if (!lastModified.isBefore(cutoff)) {
return CleanupResult.RECENT;
}
storage.remove(objectKey);
return CleanupResult.DELETED;
}
public enum CleanupResult {
DELETED,
REFERENCED,
RECENT,
BUSY,
MISSING,
SKIPPED
}
}