base of lab 4
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user