Improve notifications to display live progress for ongoing batch metadata fetches (#1242)

This commit is contained in:
Aditya Chandel
2025-09-30 14:31:14 -06:00
committed by GitHub
parent 131b19f49f
commit 879d147e84
19 changed files with 187 additions and 326 deletions
@@ -11,4 +11,5 @@ public class MetadataBatchProgressNotification {
private int total;
private String message;
private String status;
private boolean isReview;
}
@@ -13,7 +13,6 @@ public enum Topic {
BOOK_METADATA_BATCH_PROGRESS("/queue/book-metadata-batch-progress"),
BOOKDROP_FILE("/queue/bookdrop-file"),
DUPLICATE_FILE("/queue/duplicate-file"),
TASK("/queue/task"),
LOG("/queue/log");
private final String path;
@@ -9,6 +9,7 @@ import com.adityachandel.booklore.model.dto.response.MetadataTaskDetailsResponse
import com.adityachandel.booklore.model.entity.MetadataFetchJobEntity;
import com.adityachandel.booklore.model.entity.MetadataFetchProposalEntity;
import com.adityachandel.booklore.model.enums.FetchedMetadataProposalStatus;
import com.adityachandel.booklore.model.enums.MetadataFetchTaskStatus;
import com.adityachandel.booklore.repository.MetadataFetchJobRepository;
import com.adityachandel.booklore.repository.MetadataFetchProposalRepository;
import lombok.RequiredArgsConstructor;
@@ -30,25 +31,27 @@ public class MetadataTaskService {
public Optional<MetadataTaskDetailsResponse> getTaskWithProposals(String taskId) {
return metadataFetchTaskRepository.findById(taskId)
.map(task -> {
List<FetchedProposal> proposals = task.getProposals().stream()
.filter(p -> p.getStatus() == FetchedMetadataProposalStatus.FETCHED)
.map(fetchedProposalMapper::toDto)
.toList();
.map(this::buildTaskDetailsResponse);
}
MetadataFetchTask taskDto = MetadataFetchTask.builder()
.id(task.getTaskId())
.status(task.getStatus())
.completed(task.getCompletedBooks())
.totalBooks(task.getTotalBooksCount())
.startedAt(task.getStartedAt())
.completedAt(task.getCompletedAt())
.initiatedBy(task.getUserId())
.proposals(proposals)
.build();
private MetadataTaskDetailsResponse buildTaskDetailsResponse(MetadataFetchJobEntity task) {
List<FetchedProposal> proposals = task.getProposals().stream()
.filter(p -> p.getStatus() == FetchedMetadataProposalStatus.FETCHED)
.map(fetchedProposalMapper::toDto)
.toList();
return new MetadataTaskDetailsResponse(taskDto);
});
MetadataFetchTask taskDto = MetadataFetchTask.builder()
.id(task.getTaskId())
.status(task.getStatus())
.completed(task.getCompletedBooks())
.totalBooks(task.getTotalBooksCount())
.startedAt(task.getStartedAt())
.completedAt(task.getCompletedAt())
.initiatedBy(task.getUserId())
.proposals(proposals)
.build();
return new MetadataTaskDetailsResponse(taskDto);
}
@Transactional
@@ -87,16 +90,17 @@ public class MetadataTaskService {
}
public List<MetadataBatchProgressNotification> getActiveTasks() {
List<MetadataFetchJobEntity> tasks = metadataFetchTaskRepository.findAllWithProposals(); // Ensure this uses a fetch join
List<MetadataFetchJobEntity> tasks = metadataFetchTaskRepository.findAllWithProposals();
return tasks.stream()
.filter(task -> task.getStatus() == MetadataFetchTaskStatus.COMPLETED || task.getStatus() == MetadataFetchTaskStatus.ERROR)
.map(task -> {
List<MetadataFetchProposalEntity> proposals = task.getProposals();
List<MetadataFetchProposalEntity> remaining = proposals.stream()
.filter(p -> p.getStatus() != FetchedMetadataProposalStatus.REJECTED)
.toList();
int total = remaining.size();
int total;
long acceptedCount = remaining.stream()
.filter(p -> p.getStatus() == FetchedMetadataProposalStatus.ACCEPTED)
.count();
@@ -104,14 +108,28 @@ public class MetadataTaskService {
.filter(p -> p.getStatus() == FetchedMetadataProposalStatus.FETCHED)
.count();
String message = String.format("Metadata review pending for %d of %d books", fetchedCount, total);
String message;
String status;
int completedCount = task.getCompletedBooks() != null ? task.getCompletedBooks() : 0;
if (task.getStatus() == MetadataFetchTaskStatus.ERROR) {
total = task.getTotalBooksCount() != null ? task.getTotalBooksCount() : remaining.size();
message = String.format("Metadata fetch failed, processed %d of %d books.", completedCount, total);
status = "ERROR";
} else {
total = remaining.size();
message = String.format("Metadata fetch completed! %d books need review.", fetchedCount);
status = "COMPLETED";
completedCount = (int) acceptedCount;
}
return new MetadataBatchProgressNotification(
task.getTaskId(),
(int) acceptedCount,
completedCount,
total,
message,
"COMPLETED"
status,
true
);
})
.filter(n -> n.getTotal() > 0)
@@ -54,6 +54,8 @@ public class MetadataRefreshService {
public void refreshMetadata(MetadataRefreshRequest request, Long userId, String jobId) {
final Set<Long> bookIds = null;
final int totalBooks;
try {
AppSettings appSettings = appSettingService.getAppSettings();
@@ -66,43 +68,39 @@ public class MetadataRefreshService {
prepareProviders(requestRefreshOptions) :
(isLibraryRefresh ? prepareProviders(libraryRefreshOptions) : null);
Set<Long> bookIds = getBookEntities(request);
final Set<Long> actualBookIds = getBookEntities(request);
totalBooks = actualBookIds.size();
MetadataRefreshOptions reviewModeOptions = requestRefreshOptions != null ?
requestRefreshOptions :
(libraryRefreshOptions != null ? libraryRefreshOptions : appSettings.getDefaultMetadataRefreshOptions());
boolean isReviewMode = Boolean.TRUE.equals(reviewModeOptions.getReviewBeforeApply());
MetadataFetchJobEntity task;
if (isReviewMode) {
task = MetadataFetchJobEntity.builder()
.taskId(jobId)
.userId(userId)
.status(MetadataFetchTaskStatus.IN_PROGRESS)
.startedAt(Instant.now())
.totalBooksCount(bookIds.size())
.completedBooks(0)
.build();
metadataFetchJobRepository.save(task);
} else {
task = null;
}
MetadataFetchJobEntity task = MetadataFetchJobEntity.builder()
.taskId(jobId)
.userId(userId)
.status(MetadataFetchTaskStatus.IN_PROGRESS)
.startedAt(Instant.now())
.totalBooksCount(totalBooks)
.completedBooks(0)
.build();
metadataFetchJobRepository.save(task);
TransactionTemplate txTemplate = new TransactionTemplate(transactionManager);
int completedCount = 0;
for (Long bookId : bookIds) {
checkForInterruption(jobId, task, bookIds.size());
for (Long bookId : actualBookIds) {
checkForInterruption(jobId, task, totalBooks);
int finalCompletedCount = completedCount;
txTemplate.execute(status -> {
BookEntity book = bookRepository.findAllWithMetadataByIds(Collections.singleton(bookId))
.stream().findFirst()
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
try {
checkForInterruption(jobId, task, bookIds.size());
checkForInterruption(jobId, task, totalBooks);
if (book.getMetadata().areAllFieldsLocked()) {
log.info("Skipping locked book: {}", book.getFileName());
sendTaskNotification(jobId, "Skipped locked book: " + book.getMetadata().getTitle(), TaskStatus.IN_PROGRESS);
sendBatchProgressNotification(jobId, finalCompletedCount, totalBooks, "Skipped locked book: " + book.getMetadata().getTitle(), MetadataFetchTaskStatus.IN_PROGRESS, isReviewMode);
return null;
}
@@ -120,7 +118,7 @@ public class MetadataRefreshService {
providers = prepareProviders(refreshOptions);
}
reportProgressIfNeeded(task, jobId, finalCompletedCount, bookIds.size(), book);
reportProgressIfNeeded(task, jobId, finalCompletedCount, totalBooks, book, isReviewMode);
Map<MetadataProvider, BookMetadata> metadataMap = fetchMetadataForBook(providers, book);
if (providers.contains(GoodReads)) {
try {
@@ -138,8 +136,9 @@ public class MetadataRefreshService {
saveProposal(task, book.getId(), fetched);
} else {
updateBookMetadata(book, fetched, refreshOptions.isRefreshCovers(), refreshOptions.isMergeCategories());
sendTaskProgressNotification(jobId, finalCompletedCount + 1, bookIds.size(), "Metadata updated: " + book.getMetadata().getTitle());
}
sendBatchProgressNotification(jobId, finalCompletedCount + 1, totalBooks, "Processed: " + book.getMetadata().getTitle(), MetadataFetchTaskStatus.IN_PROGRESS, bookReviewMode);
} catch (Exception e) {
if (Thread.currentThread().isInterrupted()) {
log.info("Processing interrupted for book: {}", book.getFileName());
@@ -147,7 +146,7 @@ public class MetadataRefreshService {
return null;
}
log.error("Metadata update failed for book: {}", book.getFileName(), e);
sendTaskNotification(jobId, String.format("Failed to process: %s - %s", book.getMetadata().getTitle(), e.getMessage()), TaskStatus.FAILED);
sendBatchProgressNotification(jobId, finalCompletedCount, totalBooks, String.format("Failed to process: %s - %s", book.getMetadata().getTitle(), e.getMessage()), MetadataFetchTaskStatus.ERROR, isReviewMode);
}
bookRepository.saveAndFlush(book);
return null;
@@ -155,22 +154,22 @@ public class MetadataRefreshService {
completedCount++;
}
if (isReviewMode) completeTask(task, completedCount, bookIds.size());
completeTask(task, completedCount, totalBooks, isReviewMode);
log.info("Metadata refresh task {} completed successfully", jobId);
sendTaskNotification(jobId, String.format("Metadata refresh completed successfully - processed %d books", completedCount), TaskStatus.COMPLETED);
} catch (RuntimeException e) {
if (e.getCause() instanceof InterruptedException) {
log.info("Metadata refresh task {} cancelled successfully", jobId);
return;
}
log.error("Fatal error during metadata refresh", e);
sendTaskNotification(jobId, "Fatal error during metadata refresh: " + e.getMessage(), TaskStatus.FAILED);
int totalBooksForError = 0;
sendBatchProgressNotification(jobId, 0, totalBooksForError, "Fatal error during metadata refresh: " + e.getMessage(), MetadataFetchTaskStatus.ERROR, false);
throw e;
} catch (Exception fatal) {
log.error("Fatal error during metadata refresh", fatal);
sendTaskNotification(jobId, "Fatal error during metadata refresh: " + fatal.getMessage(), TaskStatus.FAILED);
int totalBooksForError = bookIds != null ? bookIds.size() : 0;
sendBatchProgressNotification(jobId, 0, totalBooksForError, "Fatal error during metadata refresh: " + fatal.getMessage(), MetadataFetchTaskStatus.ERROR, false);
throw fatal;
}
}
@@ -247,7 +246,7 @@ public class MetadataRefreshService {
private void checkForInterruption(String jobId, MetadataFetchJobEntity task, int totalBooks) {
if (Thread.currentThread().isInterrupted()) {
log.info("Metadata refresh task {} cancelled by user request", jobId);
sendTaskNotification(jobId, "Task cancelled by user", TaskStatus.CANCELLED);
sendBatchProgressNotification(jobId, 0, totalBooks, "Task cancelled by user", MetadataFetchTaskStatus.ERROR, false);
if (task != null) {
failTask(task, totalBooks);
}
@@ -255,53 +254,35 @@ public class MetadataRefreshService {
}
}
private void sendTaskNotification(String taskId, String message, TaskStatus status) {
notificationService.sendMessage(Topic.TASK, TaskMessage.builder()
.taskId(taskId)
.taskType(EventTaskType.METADATA_REFRESH)
.message(message)
.status(status)
.build());
}
private void sendTaskProgressNotification(String taskId, int current, int total, String message) {
sendTaskNotification(taskId, String.format("(%d/%d) %s", current, total, message), TaskStatus.IN_PROGRESS);
}
private void reportProgressIfNeeded(MetadataFetchJobEntity task, String taskId, int completedCount, int total, BookEntity book) {
private void reportProgressIfNeeded(MetadataFetchJobEntity task, String taskId, int completedCount, int total, BookEntity book, boolean isReviewMode) {
if (task == null) return;
task.setCompletedBooks(completedCount);
metadataFetchJobRepository.save(task);
String message = String.format("Processing '%s'", book.getMetadata().getTitle());
sendBatchProgressNotification(taskId, completedCount, total, message, MetadataFetchTaskStatus.IN_PROGRESS, isReviewMode);
}
private void sendBatchProgressNotification(String taskId, int current, int total, String message, MetadataFetchTaskStatus status, boolean isReview) {
notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_PROGRESS,
new MetadataBatchProgressNotification(
taskId, completedCount, total, message, MetadataFetchTaskStatus.IN_PROGRESS.name()
taskId, current, total, message, status.name(), isReview
));
}
private void completeTask(MetadataFetchJobEntity task, int completed, int total) {
private void completeTask(MetadataFetchJobEntity task, int completed, int total, boolean isReviewMode) {
task.setStatus(MetadataFetchTaskStatus.COMPLETED);
task.setCompletedAt(Instant.now());
task.setCompletedBooks(completed);
metadataFetchJobRepository.save(task);
notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_PROGRESS,
new MetadataBatchProgressNotification(
task.getTaskId(), completed, total, "Metadata batch update completed",
MetadataFetchTaskStatus.COMPLETED.name()
));
sendBatchProgressNotification(task.getTaskId(), completed, total, "Batch metadata fetch successfully completed!", MetadataFetchTaskStatus.COMPLETED, isReviewMode);
}
private void failTask(MetadataFetchJobEntity task, int total) {
task.setStatus(MetadataFetchTaskStatus.ERROR);
task.setCompletedAt(Instant.now());
metadataFetchJobRepository.save(task);
notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_PROGRESS,
new MetadataBatchProgressNotification(
task.getTaskId(), 0, total, "Error: " + "Task was cancelled",
MetadataFetchTaskStatus.ERROR.name()
));
sendBatchProgressNotification(task.getTaskId(), 0, total, "Error: " + "Task was cancelled", MetadataFetchTaskStatus.ERROR, false);
}
private void saveProposal(MetadataFetchJobEntity job, Long bookId, BookMetadata metadata) throws JsonProcessingException {
@@ -550,4 +531,3 @@ public class MetadataRefreshService {
};
}
}