Implement task scheduling system (#1427)

* Implement task scheduling system

* Remove tests
This commit is contained in:
Aditya Chandel
2025-10-23 22:49:42 -06:00
committed by GitHub
parent 2f6ae855dd
commit 5fe62ac576
130 changed files with 3355 additions and 1608 deletions
@@ -14,7 +14,7 @@ export class TaskHelperService {
refreshMetadataTask(options: MetadataRefreshRequest) {
const request: TaskCreateRequest = {
taskType: TaskType.REFRESH_METADATA,
taskType: TaskType.REFRESH_METADATA_MANUAL,
options
};
return this.taskService.startTask(request).pipe(
@@ -6,264 +6,215 @@
<app-external-doc-link docType="taskManagement"></app-external-doc-link>
</h2>
<p class="settings-description">
Monitor and manage system tasks including cache operations, library scanning, and other background processes.
Manage automated system tasks for library maintenance, metadata refreshing, and cache cleanup.
Execute tasks manually, monitor their progress in real-time, and schedule recurring operations using
<a href="https://spring.io/blog/2020/11/10/new-in-spring-5-3-improved-cron-expressions" target="_blank" rel="noopener noreferrer" style="color: #3b82f6;">Spring cron expressions</a>.
</p>
</div>
<div class="settings-content">
<div class="preferences-section">
<div class="section-header">
<div class="section-header-content">
<h3 class="section-title">
<i class="pi pi-cog"></i>
One-Time Tasks
</h3>
<p-button
label="Refresh"
icon="pi pi-refresh"
size="small"
outlined
[loading]="loading"
(onClick)="loadTasks()">
</p-button>
</div>
</div>
@if (loading && tasks.length === 0) {
@if (loading && taskInfos.length === 0) {
<div class="loading-container">
<i class="pi pi-spin pi-spinner"></i>
<span>Loading tasks...</span>
</div>
}
@for (task of tasks; track task.type) {
@if (task.type === TaskType.CLEAR_CBX_CACHE || task.type === TaskType.CLEAR_PDF_CACHE) {
<div class="settings-card" [class.compact]="!isTaskRunning(task)">
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<div class="task-title-section">
<div class="title-with-status">
<label class="setting-label">
<i class="pi pi-trash"></i>
{{ getTaskDisplayName(task.type) }}
</label>
@if (!isTaskRunning(task) && task.id) {
<span class="last-run-badge">[{{ getLastRunMessage(task) }}<span class="sep">|</span><span class="status-dot" [ngClass]="getLastRunInfoClass(task.status)"></span><span
class="status-text">{{ getLastRunInfoClass(task.status) === 'success' ? 'Success' : getLastRunInfoClass(task.status) === 'error' ? 'Error' : getLastRunInfoClass(task.status) === 'warning' ? 'Warning' : 'Info' }}]</span></span>
}
</div>
@if (!isTaskRunning(task)) {
<p class="setting-description compact">
{{ getTaskDescription(task.type) }}
</p>
}
@if (!isTaskRunning(task) && hasMetadata(task)) {
<div class="task-metadata prominent">
@if (task.metadata.currentCacheSize) {
<span class="metadata-item prominent">
<i class="pi pi-database"></i>
Current cache size:
<span class="cache-size-value">{{ task.metadata.currentCacheSize }}</span>
</span>
}
</div>
@for (taskInfo of taskInfos; track taskInfo.taskType) {
<div class="settings-card" [class.compact]="!isTaskRunning(taskInfo.taskType)">
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<div class="task-title-section">
<div class="title-with-status">
<label class="setting-label">
<i class="pi" [ngClass]="getTaskIcon(taskInfo.taskType)"></i>
{{ getTaskLabel(taskInfo.taskType) }}
</label>
@if (!isTaskRunning(taskInfo.taskType) && getTaskHistory(taskInfo.taskType)?.id) {
<span class="last-run-badge">[{{ getLastRunMessage(taskInfo.taskType) }}<span class="sep">|</span><span class="status-dot" [ngClass]="getLastRunInfoClass(taskInfo.taskType)"></span><span
class="status-text">{{ getLastRunInfoClass(taskInfo.taskType) === 'success' ? 'Success' : getLastRunInfoClass(taskInfo.taskType) === 'error' ? 'Error' : getLastRunInfoClass(taskInfo.taskType) === 'warning' ? 'Warning' : 'Info' }}]</span></span>
}
</div>
<div class="task-actions">
@if (isTaskRunning(task) && !isTaskStale(task)) {
<p-badge
value="In Progress"
severity="info">
</p-badge>
}
@if (isTaskStale(task)) {
<p-badge
value="Stale"
severity="warn">
</p-badge>
}
@if (canExecuteTask(task) || isTaskStale(task)) {
<p-button
label="Clear Cache"
icon="pi pi-trash"
size="small"
severity="warn"
(onClick)="executeTask(task)">
</p-button>
}
@if (canCancelTask(task) && !isTaskStale(task)) {
<p-button
label="Cancel"
icon="pi pi-times"
size="small"
severity="danger"
outlined
(onClick)="cancelTask(task)">
</p-button>
}
</div>
</div>
@if (isTaskRunning(task)) {
<div class="task-details" [class.stale]="isTaskStale(task)">
@if (isTaskStale(task)) {
<div class="task-info-row stale-warning">
<span class="task-info-label">
<i class="pi pi-exclamation-triangle"></i>
Warning:
</span>
<span class="task-info-value warning-text">
This task appears to be stuck. No updates received for over 10 minutes.
</span>
</div>
}
@if (task.message || isTaskStale(task)) {
<div class="task-info-row">
<span class="task-info-label">Status:</span>
<span class="task-info-value">{{ getTaskStatusMessage(task) }}</span>
</div>
}
@if (task.progressPercentage !== null) {
<div class="task-info-row">
<span class="task-info-label">Progress:</span>
<div class="progress-container">
<p-progressbar [value]="task.progressPercentage"></p-progressbar>
<span class="progress-text">{{ task.progressPercentage }}%</span>
</div>
</div>
}
@if (task.updatedAt) {
<div class="task-info-row">
<span class="task-info-label">Started:</span>
<span class="task-info-value">{{ formatDate(task.updatedAt) }}</span>
</div>
}
</div>
<p class="setting-description expanded">
<i class="pi pi-info-circle"></i>
{{ getTaskDescription(task.type) }}
<p class="setting-description" [class.compact]="!isTaskRunning(taskInfo.taskType)" [class.expanded]="isTaskRunning(taskInfo.taskType)">
{{ getTaskDescription(taskInfo.taskType) }}
</p>
}
</div>
</div>
</div>
}
@if (task.type === TaskType.RE_SCAN_LIBRARY) {
<div class="settings-card" [class.compact]="!isTaskRunning(task)">
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<div class="task-title-section">
<div class="title-with-status">
<label class="setting-label">
<i class="pi pi-sync"></i>
{{ getTaskDisplayName(task.type) }}
</label>
@if (!isTaskRunning(task) && task.id) {
<span class="last-run-badge">[{{ getLastRunMessage(task) }}<span class="sep">|</span><span class="status-dot" [ngClass]="getLastRunInfoClass(task.status)"></span><span
class="status-text">{{ getLastRunInfoClass(task.status) === 'success' ? 'Success' : getLastRunInfoClass(task.status) === 'error' ? 'Error' : getLastRunInfoClass(task.status) === 'warning' ? 'Warning' : 'Info' }}]</span></span>
}
@if (!isTaskRunning(taskInfo.taskType) && hasMetadata(taskInfo.taskType)) {
<div class="task-metadata prominent">
<span class="metadata-item prominent">
<i class="pi" [ngClass]="getMetadataIcon(taskInfo.taskType)"></i>
{{ getTaskMetadata(taskInfo.taskType) }}
</span>
</div>
<p class="setting-description compact always-visible">
{{ getTaskDescription(task.type) }}
</p>
@if (!isTaskRunning(task)) {
<div class="task-options">
<div class="option-group">
}
@if (!isTaskRunning(taskInfo.taskType) && taskInfo.taskType === TaskType.REFRESH_LIBRARY_METADATA) {
<div class="task-options">
<div class="option-group">
<div class="option-row">
<label class="option-label">Metadata Replace Mode:</label>
<p-select
[options]="metadataReplaceOptions"
[(ngModel)]="selectedMetadataReplaceMode"
size="small"
optionLabel="label"
optionValue="value"
placeholder="Select mode"
class="metadata-select">
</p-select>
<p class="option-description">
{{ getMetadataReplaceDescription(selectedMetadataReplaceMode) }}
</p>
</div>
<p class="option-description">
{{ getMetadataReplaceDescription(selectedMetadataReplaceMode) }}
</p>
</div>
}
</div>
<div class="task-actions">
@if (isTaskRunning(task) && !isTaskStale(task)) {
<p-badge
value="In Progress"
severity="info">
</p-badge>
}
@if (isTaskStale(task)) {
<p-badge
value="Stale"
severity="warn">
</p-badge>
}
@if (canExecuteTask(task) || isTaskStale(task)) {
<p-button
label="Start Refresh"
icon="pi pi-sync"
size="small"
severity="success"
(onClick)="executeTask(task)">
</p-button>
}
@if (canCancelTask(task) && !isTaskStale(task)) {
<p-button
label="Cancel"
icon="pi pi-times"
size="small"
severity="danger"
outlined
(onClick)="cancelTask(task)">
</p-button>
}
</div>
</div>
}
</div>
@if (isTaskRunning(task)) {
<div class="task-details" [class.stale]="isTaskStale(task)">
@if (isTaskStale(task)) {
<div class="task-info-row stale-warning">
<span class="task-info-label">
<i class="pi pi-exclamation-triangle"></i>
Warning:
</span>
<span class="task-info-value warning-text">
This task appears to be stuck. No updates received for over 10 minutes.
</span>
</div>
}
@if (task.message || isTaskStale(task)) {
<div class="task-info-row">
<span class="task-info-label">Status:</span>
<span class="task-info-value">{{ getTaskStatusMessage(task) }}</span>
</div>
}
@if (task.progressPercentage !== null) {
<div class="task-info-row">
<span class="task-info-label">Progress:</span>
<div class="progress-container">
<p-progressbar [value]="task.progressPercentage"></p-progressbar>
<span class="progress-text">{{ task.progressPercentage }}%</span>
@if (!isTaskRunning(taskInfo.taskType) && isCronSupported(taskInfo.taskType) && getCronConfig(taskInfo.taskType)) {
<div class="cron-config-section compact">
<i class="pi pi-clock"></i>
<span class="cron-label">Scheduled:</span>
@if (!isEditingCron(taskInfo.taskType)) {
@if (getCronConfig(taskInfo.taskType).cronExpression) {
<span class="cron-expression">{{ getCronConfig(taskInfo.taskType).cronExpression }}</span>
} @else {
<span class="cron-expression empty">Not configured</span>
}
<p-button
icon="pi pi-pencil"
size="small"
[text]="true"
[rounded]="true"
severity="info"
[disabled]="cronUpdating"
pTooltip="Edit Schedule"
tooltipPosition="top"
(onClick)="startEditingCron(taskInfo.taskType)">
</p-button>
} @else {
<div class="cron-edit-section">
<div class="cron-input-wrapper">
<input
type="text"
class="cron-input"
[class.error]="!!cronValidationError"
[(ngModel)]="editingCronExpression"
(ngModelChange)="onCronExpressionChange()"
placeholder="e.g., 0 2 * * *"
(keyup.enter)="saveCronExpression(taskInfo.taskType)"
(keyup.escape)="cancelEditingCron()">
@if (cronValidationError) {
<div class="cron-error">
<i class="pi pi-exclamation-circle"></i>
<span>{{ cronValidationError }}</span>
</div>
}
</div>
<div class="cron-actions">
<p-button
[icon]="cronUpdating ? 'pi pi-spinner pi-spin' : 'pi pi-check'"
size="small"
[rounded]="true"
severity="success"
[disabled]="!!cronValidationError || cronUpdating"
(onClick)="saveCronExpression(taskInfo.taskType)">
</p-button>
<p-button
icon="pi pi-times"
size="small"
[rounded]="true"
severity="secondary"
(onClick)="cancelEditingCron()">
</p-button>
</div>
</div>
}
@if (task.updatedAt) {
<div class="task-info-row">
<span class="task-info-label">Started:</span>
<span class="task-info-value">{{ formatDate(task.updatedAt) }}</span>
</div>
}
<p-toggleswitch
[ngModel]="getCronConfig(taskInfo.taskType).enabled"
[disabled]="isEditingCron(taskInfo.taskType) || cronUpdating"
(ngModelChange)="toggleCronEnabled(taskInfo.taskType)">
</p-toggleswitch>
</div>
}
<div class="task-actions">
@if (isTaskRunning(taskInfo.taskType) && !isTaskStale(getTaskHistory(taskInfo.taskType))) {
<p-badge
value="In Progress"
severity="info">
</p-badge>
}
@if (isTaskStale(getTaskHistory(taskInfo.taskType))) {
<p-badge
value="Stale"
severity="warn">
</p-badge>
}
@if (canExecuteTask(taskInfo.taskType) || isTaskStale(getTaskHistory(taskInfo.taskType))) {
<p-button
[label]="getTaskButtonLabel(taskInfo.taskType)"
[icon]="getTaskButtonIcon(taskInfo.taskType)"
size="small"
severity="success"
[disabled]="isTaskExecuting(taskInfo.taskType)"
(onClick)="executeTask(taskInfo.taskType)">
</p-button>
}
@if (canCancelTask(getTaskHistory(taskInfo.taskType)) && !isTaskStale(getTaskHistory(taskInfo.taskType))) {
<p-button
label="Cancel"
[icon]="getCancelButtonIcon(taskInfo.taskType)"
size="small"
severity="danger"
outlined
[disabled]="isTaskExecuting(taskInfo.taskType)"
(onClick)="cancelTask(taskInfo.taskType)">
</p-button>
}
</div>
</div>
@if (isTaskRunning(taskInfo.taskType)) {
<div class="task-details" [class.stale]="isTaskStale(getTaskHistory(taskInfo.taskType))">
@if (isTaskStale(getTaskHistory(taskInfo.taskType))) {
<div class="task-info-row stale-warning">
<span class="task-info-label">
<i class="pi pi-exclamation-triangle"></i>
Warning:
</span>
<span class="task-info-value warning-text">
This task appears to be stuck. No updates received for over 5 minutes.
</span>
</div>
}
@if (getTaskHistory(taskInfo.taskType)?.message || isTaskStale(getTaskHistory(taskInfo.taskType))) {
<div class="task-info-row">
<span class="task-info-label">Status:</span>
<span class="task-info-value">{{ getTaskStatusMessage(taskInfo.taskType) }}</span>
</div>
}
@if (getTaskProgressPercentage(taskInfo.taskType) !== null) {
<div class="task-info-row">
<span class="task-info-label">Progress:</span>
<div class="progress-container">
<p-progressbar [value]="getTaskProgressPercentage(taskInfo.taskType)!"></p-progressbar>
<span class="progress-text">{{ getTaskProgressPercentage(taskInfo.taskType) }}%</span>
</div>
</div>
}
@if (getTaskUpdatedAt(taskInfo.taskType)) {
<div class="task-info-row">
<span class="task-info-label">Started:</span>
<span class="task-info-value">{{ formatDate(getTaskUpdatedAt(taskInfo.taskType)!) }}</span>
</div>
}
</div>
}
</div>
</div>
}
</div>
}
@if (!loading && tasks.length === 0) {
@if (!loading && taskInfos.length === 0) {
<div class="settings-card">
<div class="setting-item">
<div class="setting-info">
@@ -18,7 +18,7 @@
.settings-header {
margin-top: 1rem;
margin-bottom: 1.5rem;
margin-bottom: 3rem;
}
.settings-title {
@@ -91,7 +91,7 @@
border-radius: 8px;
background: var(--p-content-background);
padding: 1.25rem 1.5rem 1.25rem 1.5rem;
margin-bottom: 1rem;
margin-bottom: 2rem;
transition: all 0.2s ease;
&.compact {
@@ -136,6 +136,7 @@
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
margin-bottom: 0.5rem;
.setting-label {
margin-bottom: 0;
@@ -175,13 +176,11 @@
margin: 0;
&.compact {
font-size: 0.875rem;
color: var(--p-text-muted-color);
margin-top: 0.5rem;
margin-top: 0;
}
&.expanded {
margin-top: 1rem;
margin-top: 0;
}
.pi {
@@ -198,7 +197,7 @@
}
.task-details {
margin-bottom: 1rem;
margin-bottom: 0;
margin-top: 1rem;
padding: 1rem;
border-radius: 6px;
@@ -210,7 +209,6 @@
&.stale {
border-color: var(--p-yellow-500);
background: var(--p-yellow-50);
}
}
@@ -226,9 +224,9 @@
&.stale-warning {
padding: 0.5rem;
background: var(--p-yellow-100);
background: var(--p-yellow-200);
border-radius: 4px;
border: 1px solid var(--p-yellow-300);
border: 1px solid var(--p-yellow-400);
margin-bottom: 0.75rem;
.task-info-label {
@@ -342,22 +340,18 @@
&.success {
border-left-color: var(--p-green-500);
background: var(--p-green-50);
}
&.error {
border-left-color: var(--p-red-500);
background: var(--p-red-50);
}
&.warning {
border-left-color: var(--p-yellow-500);
background: var(--p-yellow-50);
}
&.info {
border-left-color: var(--p-blue-500);
background: var(--p-blue-50);
}
.last-run-text {
@@ -439,18 +433,190 @@
width: 100%;
max-width: 45rem;
border-radius: 6px;
background: var(--p-surface-800);
border: 1px solid var(--p-content-border-color);
}
.cron-config-section {
margin-top: 0;
padding: 1rem;
background: var(--p-surface-800);
border: 1px solid var(--p-content-border-color);
border-radius: 6px;
max-width: 45rem;
&.compact {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.0rem 0.5rem;
flex-wrap: nowrap;
background: var(--p-surface-800);
border: 1px solid var(--p-surface-600);
margin-top: 0;
.pi-clock {
color: var(--p-primary-color);
font-size: 1rem;
flex-shrink: 0;
}
.cron-label {
font-size: 0.875rem;
color: var(--text-color-secondary);
font-weight: 500;
flex-shrink: 0;
}
.cron-expression {
font-size: 0.85rem;
font-family: 'SF Mono', 'Monaco', 'Courier New', monospace;
color: var(--p-blue-400);
background: var(--p-surface-900);
padding: 0.375rem 0.625rem;
border-radius: 4px;
border: 1px solid var(--p-surface-700);
min-width: 120px;
letter-spacing: 0.02em;
flex-shrink: 0;
&.empty {
color: var(--p-text-muted-color);
font-style: italic;
}
}
.cron-edit-section {
display: flex;
align-items: flex-start;
gap: 0.5rem;
flex: 1;
flex-wrap: nowrap;
.cron-input-wrapper {
display: flex;
flex-direction: column;
gap: 0.5rem;
flex: 1;
min-width: 0;
}
.cron-input {
font-size: 0.8125rem;
font-family: 'SF Mono', 'Monaco', 'Courier New', monospace;
color: var(--p-text-color);
background: var(--p-surface-900);
padding: 0.375rem 0.625rem;
border-radius: 4px;
border: 1px solid var(--p-surface-700);
width: 100%;
outline: none;
transition: border-color 0.2s;
&:focus {
border-color: var(--p-primary-color);
}
&.error {
border-color: var(--p-red-500);
}
}
.cron-error {
display: flex;
align-items: flex-start;
gap: 0.5rem;
font-size: 0.75rem;
color: var(--p-orange-400);
padding: 0.375rem 0.5rem;
border: 1px solid var(--p-orange-500);
border-radius: 4px;
line-height: 1.4;
.pi {
font-size: 0.875rem;
margin-top: 0.0625rem;
flex-shrink: 0;
}
span {
flex: 1;
}
}
.cron-actions {
display: flex;
gap: 0.25rem;
flex-shrink: 0;
}
}
}
.cron-header {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 0.75rem;
color: var(--p-text-color);
font-weight: 600;
.pi {
color: var(--p-primary-color);
font-size: 1rem;
}
.cron-title {
font-size: 0.95rem;
flex: 1;
}
}
.cron-details {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.cron-item {
display: flex;
align-items: center;
gap: 0.75rem;
.cron-label {
font-size: 0.875rem;
color: var(--p-text-muted-color);
min-width: 80px;
font-weight: 500;
}
.cron-value {
font-size: 0.875rem;
font-family: 'Courier New', monospace;
color: var(--p-text-color);
background: var(--p-surface-700);
padding: 0.25rem 0.5rem;
border-radius: 4px;
border: 1px solid var(--p-surface-300);
}
}
}
.option-group {
display: flex;
flex-direction: column;
gap: 0.5rem;
.option-row {
display: flex;
align-items: center;
gap: 1rem;
}
.option-label {
font-weight: 500;
color: var(--p-text-color);
font-size: 0.9rem;
white-space: nowrap;
}
.option-description {
@@ -463,7 +629,7 @@
:host ::ng-deep .metadata-select {
width: 100%;
max-width: 400px;
max-width: 350px;
}
@media (max-width: 768px) {
@@ -500,6 +666,77 @@
gap: 0.5rem;
}
.cron-config-section {
max-width: none;
&.compact {
flex-wrap: wrap;
gap: 0.5rem;
padding: 0.75rem;
margin-top: 0.75rem;
.cron-expression {
flex: 1 1 100%;
word-break: break-all;
min-width: unset;
&.empty {
color: var(--p-text-muted-color);
}
}
.cron-edit-section {
flex: 1 1 100%;
flex-wrap: wrap;
.cron-input-wrapper {
flex: 1 1 100%;
.cron-input {
min-width: 100%;
}
}
.cron-actions {
margin-top: 0.5rem;
width: 100%;
justify-content: flex-start;
}
}
}
.cron-header {
flex-wrap: wrap;
}
.cron-item {
flex-direction: column;
align-items: flex-start;
gap: 0.25rem;
.cron-label {
min-width: auto;
}
.cron-value {
width: 100%;
word-break: break-all;
}
}
}
.option-group {
.option-row {
flex-direction: column;
align-items: flex-start;
gap: 0.5rem;
}
.option-label {
white-space: normal;
}
}
:host ::ng-deep .metadata-select {
max-width: none;
}
@@ -1,14 +1,16 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {CommonModule} from '@angular/common';
import {Button} from 'primeng/button';
import {Badge} from 'primeng/badge';
import {ProgressBar} from 'primeng/progressbar';
import {MessageService} from 'primeng/api';
import {Select} from 'primeng/select';
import {FormsModule} from '@angular/forms';
import {MetadataReplaceMode, Task, TASK_TYPE_CONFIG, TaskCreateRequest, TaskProgressPayload, TaskService, TaskStatus, TaskType} from './task.service';
import {finalize, Subscription} from 'rxjs';
import {TaskInfo, MetadataReplaceMode, TaskHistory, TASK_TYPE_CONFIG, TaskCreateRequest, TaskCronConfigRequest, TaskProgressPayload, TaskService, TaskStatus, TaskType} from './task.service';
import {finalize, forkJoin, Subscription} from 'rxjs';
import {ExternalDocLinkComponent} from '../../../shared/components/external-doc-link/external-doc-link.component';
import {ToggleSwitch} from 'primeng/toggleswitch';
import {Badge} from 'primeng/badge';
import {Tooltip} from 'primeng/tooltip';
@Component({
selector: 'app-task-management',
@@ -16,29 +18,56 @@ import {ExternalDocLinkComponent} from '../../../shared/components/external-doc-
imports: [
CommonModule,
Button,
Badge,
ProgressBar,
Select,
FormsModule,
ExternalDocLinkComponent
ExternalDocLinkComponent,
ToggleSwitch,
Badge,
Tooltip
],
templateUrl: './task-management.component.html',
styleUrl: './task-management.component.scss'
})
export class TaskManagementComponent implements OnInit, OnDestroy {
// Services
private messageService = inject(MessageService);
private taskService = inject(TaskService);
tasks: Task[] = [];
// State
taskInfos: TaskInfo[] = [];
taskHistories: Map<string, TaskHistory> = new Map();
loading = false;
executingTasks = new Set<string>();
private subscription?: Subscription;
// Metadata Replace Options
metadataReplaceOptions = [
{label: 'Replace Missing Only (Recommended)', value: MetadataReplaceMode.REPLACE_MISSING},
{label: 'Replace All Metadata', value: MetadataReplaceMode.REPLACE_ALL}
{
label: 'Update Missing Metadata Only (Recommended)',
value: MetadataReplaceMode.REPLACE_MISSING
},
{
label: 'Replace All Metadata (Overwrite Existing)',
value: MetadataReplaceMode.REPLACE_ALL
}
];
selectedMetadataReplaceMode: MetadataReplaceMode = MetadataReplaceMode.REPLACE_MISSING;
// Cron Editing State
cronUpdating = false;
editingCronTaskType: string | null = null;
editingCronExpression: string = '';
cronValidationError: string | null = null;
// Constants
private readonly STALE_TASK_THRESHOLD_MS = 5 * 60 * 1000; // 5 minutes
protected readonly TaskType = TaskType;
// ============================================================================
// Lifecycle Hooks
// ============================================================================
ngOnInit(): void {
this.loadTasks();
this.subscribeToTaskProgress();
@@ -48,6 +77,33 @@ export class TaskManagementComponent implements OnInit, OnDestroy {
this.subscription?.unsubscribe();
}
// ============================================================================
// Data Loading & Real-time Updates
// ============================================================================
loadTasks(): void {
this.loading = true;
forkJoin({
available: this.taskService.getAvailableTasks(),
latest: this.taskService.getLatestTasksForEachType()
})
.pipe(finalize(() => this.loading = false))
.subscribe({
next: ({available, latest}) => {
this.taskInfos = this.sortTasksByDisplayOrder(available);
this.taskHistories.clear();
latest.taskHistories.forEach(history => {
this.taskHistories.set(history.type, history);
});
},
error: (error) => {
console.error('Error loading tasks:', error);
this.showMessage('error', 'Error', 'Failed to load tasks');
}
});
}
private subscribeToTaskProgress(): void {
this.subscription = this.taskService.taskProgress$.subscribe(progress => {
if (progress) {
@@ -57,80 +113,59 @@ export class TaskManagementComponent implements OnInit, OnDestroy {
}
private updateTaskWithProgress(progress: TaskProgressPayload): void {
const taskIndex = this.tasks.findIndex(task => task.id === progress.taskId);
if (taskIndex !== -1) {
this.tasks[taskIndex] = {
...this.tasks[taskIndex],
status: progress.taskStatus,
progressPercentage: progress.progress,
message: progress.message,
updatedAt: new Date().toISOString()
};
const existingHistory = this.taskHistories.get(progress.taskType);
if (progress.taskStatus === TaskStatus.COMPLETED || progress.taskStatus === TaskStatus.FAILED) {
setTimeout(() => this.loadTasks(), 1000);
}
const updatedHistory: TaskHistory = {
id: progress.taskId,
type: progress.taskType,
status: progress.taskStatus,
progressPercentage: progress.progress,
message: progress.message,
createdAt: existingHistory?.createdAt || new Date().toISOString(),
updatedAt: new Date().toISOString(),
completedAt: (progress.taskStatus === TaskStatus.COMPLETED || progress.taskStatus === TaskStatus.FAILED)
? new Date().toISOString()
: existingHistory?.completedAt || null
};
this.taskHistories.set(progress.taskType, updatedHistory);
if (progress.taskStatus === TaskStatus.COMPLETED || progress.taskStatus === TaskStatus.FAILED) {
setTimeout(() => this.loadTasks(), 1000);
}
}
loadTasks(): void {
this.loading = true;
this.taskService.getLatestTasksForEachType()
.pipe(finalize(() => this.loading = false))
.subscribe({
next: (response) => {
this.tasks = response.tasks;
},
error: (error) => {
console.error('Error loading tasks:', error);
this.showMessage('error', 'Error', 'Failed to load tasks');
}
});
private sortTasksByDisplayOrder(tasks: TaskInfo[]): TaskInfo[] {
return tasks.sort((a, b) => {
const orderA = TASK_TYPE_CONFIG[a.taskType as TaskType]?.displayOrder ?? 999;
const orderB = TASK_TYPE_CONFIG[b.taskType as TaskType]?.displayOrder ?? 999;
return orderA - orderB;
});
}
getTaskDisplayName(type: string): string {
const taskNames: Record<string, string> = {
'CLEAR_CBX_CACHE': 'Clear CBX Cache',
'CLEAR_PDF_CACHE': 'Clear PDF Cache',
'RE_SCAN_LIBRARY': 'Refresh Metadata from Library Files'
};
return taskNames[type] || type.replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, l => l.toUpperCase());
// ============================================================================
// Task Execution Operations
// ============================================================================
canExecuteTask(taskType: string): boolean {
const history = this.taskHistories.get(taskType);
return this.canRunTask(history) || this.isTaskStale(history);
}
getTaskDescription(type: string): string {
const descriptions: Record<string, string> = {
'CLEAR_CBX_CACHE': 'Clears the cached images for CBX files to free up disk space.',
'CLEAR_PDF_CACHE': 'Clears the cached images for PDF files to free up disk space.',
'RE_SCAN_LIBRARY': 'Scans the library folders to read metadata from existing book files and update the database accordingly. Existing metadata in the database may be overwritten during this process.'
};
return descriptions[type] || 'System maintenance task.';
}
canExecuteTask(task: Task): boolean {
return this.canRunTask(task) || this.isTaskStale(task);
}
executeTask(task: Task): void {
this.runTask(task.type);
}
canRunTask(task: Task): boolean {
return !task.status || task.status === TaskStatus.COMPLETED || task.status === TaskStatus.FAILED || task.status === TaskStatus.CANCELLED;
}
canCancelTask(task: Task): boolean {
return task.status === TaskStatus.IN_PROGRESS || task.status === TaskStatus.PENDING;
executeTask(taskType: string): void {
this.runTask(taskType);
}
runTask(type: string): void {
if (!this.canRunTask(this.getTaskByType(type)) && !this.isTaskStale(this.getTaskByType(type))) {
const history = this.taskHistories.get(type);
if (!this.canRunTask(history) && !this.isTaskStale(history)) {
this.showMessage('warn', 'Task Already Running', 'This task is already in progress or pending.');
return;
}
let options = null;
if (type === TaskType.RE_SCAN_LIBRARY) {
if (type === TaskType.REFRESH_LIBRARY_METADATA) {
options = {
metadataReplaceMode: this.selectedMetadataReplaceMode
};
@@ -147,129 +182,410 @@ export class TaskManagementComponent implements OnInit, OnDestroy {
const isAsync = TASK_TYPE_CONFIG[type as TaskType]?.async || false;
this.taskService.startTask(request).subscribe({
next: (response) => {
if (isAsync) {
this.showMessage('info', 'Task Queued', `${this.getTaskDisplayName(type)} has been queued and will run in the background.`);
} else {
if (response.status === TaskStatus.COMPLETED) {
this.showMessage('success', 'Task Completed', `${this.getTaskDisplayName(type)} has been completed successfully.`);
} else if (response.status === TaskStatus.FAILED) {
this.showMessage('error', 'Task Failed', response.message || `${this.getTaskDisplayName(type)} failed to complete.`);
this.executingTasks.add(type);
this.taskService.startTask(request)
.pipe(finalize(() => this.executingTasks.delete(type)))
.subscribe({
next: (response) => {
if (isAsync) {
this.showMessage('info', 'Task Queued', `${this.getTaskDisplayName(type)} has been queued and will run in the background.`);
} else {
this.showMessage('success', 'Task Started', `${this.getTaskDisplayName(type)} has been started successfully.`);
if (response.status === TaskStatus.COMPLETED) {
this.showMessage('success', 'Task Completed', `${this.getTaskDisplayName(type)} has been completed successfully.`);
} else if (response.status === TaskStatus.FAILED) {
this.showMessage('error', 'Task Failed', response.message || `${this.getTaskDisplayName(type)} failed to complete.`);
} else {
this.showMessage('success', 'Task Started', `${this.getTaskDisplayName(type)} has been started successfully.`);
}
}
this.loadTasks();
},
error: (error) => {
console.error('Error starting task:', error);
this.showMessage('error', 'Error', `Failed to start ${this.getTaskDisplayName(type)}.`);
}
this.loadTasks();
},
error: (error) => {
console.error('Error starting task:', error);
this.showMessage('error', 'Error', `Failed to start ${this.getTaskDisplayName(type)}.`);
}
});
});
}
cancelTask(task: Task): void {
if (!task.id) {
cancelTask(taskType: string): void {
const history = this.taskHistories.get(taskType);
if (!history?.id) {
this.showMessage('error', 'Error', 'Cannot cancel task without ID.');
return;
}
this.taskService.cancelTask(task.id).subscribe({
next: (response) => {
if (response.cancelled) {
this.showMessage('success', 'Task Cancelled', response.message || 'Task has been cancelled successfully.');
this.loadTasks(); // Refresh the task list
} else {
this.showMessage('error', 'Cancellation Failed', response.message || 'Failed to cancel the task.');
this.executingTasks.add(taskType);
this.taskService.cancelTask(history.id)
.pipe(finalize(() => this.executingTasks.delete(taskType)))
.subscribe({
next: (response) => {
if (response.cancelled) {
this.showMessage('success', 'Task Cancelled', response.message || 'Task has been cancelled successfully.');
this.loadTasks();
} else {
this.showMessage('error', 'Cancellation Failed', response.message || 'Failed to cancel the task.');
}
},
error: (error) => {
console.error('Error cancelling task:', error);
this.showMessage('error', 'Error', 'Failed to cancel the task. The task may already be completed or failed.');
this.loadTasks();
}
},
error: (error) => {
console.error('Error cancelling task:', error);
this.showMessage('error', 'Error', 'Failed to cancel the task. The task may already be completed or failed.');
// Refresh tasks in case the task actually completed
this.loadTasks();
}
});
});
}
canRunTask(history: TaskHistory | undefined): boolean {
return !history?.status || history.status === TaskStatus.COMPLETED || history.status === TaskStatus.FAILED || history.status === TaskStatus.CANCELLED;
}
canCancelTask(history: TaskHistory | undefined): boolean {
return history?.status === TaskStatus.IN_PROGRESS || history?.status === TaskStatus.PENDING;
}
isTaskExecuting(taskType: string): boolean {
return this.executingTasks.has(taskType);
}
isTaskRunning(taskType: string): boolean {
const history = this.taskHistories.get(taskType);
return history?.status === TaskStatus.IN_PROGRESS || history?.status === TaskStatus.PENDING;
}
isTaskStale(history: TaskHistory | undefined): boolean {
if (!history || !this.isTaskRunningForHistory(history) || !history.updatedAt) {
return false;
}
const lastUpdate = new Date(history.updatedAt).getTime();
const now = Date.now();
return (now - lastUpdate) > this.STALE_TASK_THRESHOLD_MS;
}
private isTaskRunningForHistory(history: TaskHistory): boolean {
return history.status === TaskStatus.IN_PROGRESS || history.status === TaskStatus.PENDING;
}
// ============================================================================
// Cron Configuration Management
// ============================================================================
isCronSupported(taskType: string): boolean {
const taskInfo = this.taskInfos.find(t => t.taskType === taskType);
return taskInfo?.cronSupported || false;
}
getCronConfig(taskType: string): any {
const taskInfo = this.taskInfos.find(t => t.taskType === taskType);
return taskInfo?.cronConfig;
}
toggleCronEnabled(taskType: string): void {
const cronConfig = this.getCronConfig(taskType);
if (!cronConfig) return;
const request: TaskCronConfigRequest = {
enabled: !cronConfig.enabled
};
this.updateCronConfig(taskType, request);
}
isEditingCron(taskType: string): boolean {
return this.editingCronTaskType === taskType;
}
startEditingCron(taskType: string): void {
const cronConfig = this.getCronConfig(taskType);
this.editingCronTaskType = taskType;
this.editingCronExpression = cronConfig?.cronExpression || '';
this.cronValidationError = null;
this.validateCronExpression(this.editingCronExpression);
}
cancelEditingCron(): void {
this.editingCronTaskType = null;
this.editingCronExpression = '';
this.cronValidationError = null;
}
onCronExpressionChange(): void {
this.validateCronExpression(this.editingCronExpression);
}
saveCronExpression(taskType: string): void {
if (this.cronValidationError) {
return;
}
const expression = this.editingCronExpression.trim() || null;
this.updateCronExpression(taskType, expression);
this.cancelEditingCron();
}
updateCronExpression(taskType: string, expression: string | null): void {
const request: TaskCronConfigRequest = {
cronExpression: expression
};
this.updateCronConfig(taskType, request);
}
private updateCronConfig(taskType: string, request: TaskCronConfigRequest): void {
this.cronUpdating = true;
this.taskService.updateCronConfig(taskType, request)
.pipe(finalize(() => this.cronUpdating = false))
.subscribe({
next: (updatedConfig) => {
const taskInfoIndex = this.taskInfos.findIndex(t => t.taskType === taskType);
if (taskInfoIndex !== -1) {
this.taskInfos[taskInfoIndex].cronConfig = updatedConfig;
}
this.showMessage('success', 'Cron Updated', 'Scheduled task configuration has been updated successfully.');
},
error: (error) => {
console.error('Error updating cron config:', error);
this.showMessage('error', 'Error', 'Failed to update scheduled task configuration.');
}
});
}
// ============================================================================
// Cron Validation
// ============================================================================
private validateCronExpression(expression: string): void {
if (!expression || expression.trim() === '') {
this.cronValidationError = null;
return;
}
const trimmed = expression.trim();
const parts = trimmed.split(/\s+/);
if (parts.length !== 6) {
this.cronValidationError = 'Cron expression must have exactly 6 fields (seconds, minutes, hours, day, month, weekday)';
return;
}
const validations = [
{field: parts[0], name: 'Seconds', range: [0, 59]},
{field: parts[1], name: 'Minutes', range: [0, 59]},
{field: parts[2], name: 'Hours', range: [0, 23]},
{field: parts[3], name: 'Day of Month', range: [1, 31]},
{field: parts[4], name: 'Month', range: [1, 12]},
{field: parts[5], name: 'Day of Week', range: [0, 7]}
];
for (const validation of validations) {
if (!this.isValidCronField(validation.field, validation.range[0], validation.range[1])) {
this.cronValidationError = `Invalid ${validation.name} field: ${validation.field}`;
return;
}
}
this.cronValidationError = null;
}
private isValidCronField(field: string, min: number, max: number): boolean {
if (field === '*' || field === '?') {
return true;
}
if (field.includes('-')) {
const [start, end] = field.split('-').map(Number);
return !isNaN(start) && !isNaN(end) && start >= min && end <= max && start <= end;
}
if (field.includes('/')) {
const [range, step] = field.split('/');
const stepNum = Number(step);
if (isNaN(stepNum) || stepNum <= 0) return false;
if (range === '*') return true;
if (range.includes('-')) {
const [start, end] = range.split('-').map(Number);
return !isNaN(start) && !isNaN(end) && start >= min && end <= max;
}
return false;
}
if (field.includes(',')) {
const values = field.split(',').map(Number);
return values.every(val => !isNaN(val) && val >= min && val <= max);
}
const num = Number(field);
return !isNaN(num) && num >= min && num <= max;
}
// ============================================================================
// UI Helper Methods - Task Information
// ============================================================================
getTaskDisplayName(type: string): string {
const taskInfo = this.taskInfos.find(t => t.taskType === type);
return taskInfo?.name || type.replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, l => l.toUpperCase());
}
getTaskDescription(type: string): string {
const taskInfo = this.taskInfos.find(t => t.taskType === type);
return taskInfo?.description || 'System maintenance task.';
}
getTaskDisplayOrder(type: string): number {
return TASK_TYPE_CONFIG[type as TaskType]?.displayOrder ?? 999;
}
getTaskLabel(taskType: string): string {
return `${this.getTaskDisplayOrder(taskType)}. ${this.getTaskDisplayName(taskType)}`;
}
getTaskIcon(taskType: string): string {
const icons: Record<string, string> = {
[TaskType.CLEAR_CBX_CACHE]: 'pi-database',
[TaskType.CLEAR_PDF_CACHE]: 'pi-database',
[TaskType.REFRESH_LIBRARY_METADATA]: 'pi-refresh',
[TaskType.UPDATE_BOOK_RECOMMENDATIONS]: 'pi-sparkles',
[TaskType.CLEANUP_DELETED_BOOKS]: 'pi-trash',
[TaskType.SYNC_LIBRARY_FILES]: 'pi-sync',
[TaskType.CLEANUP_TEMP_METADATA]: 'pi-file'
};
return icons[taskType] || 'pi-cog';
}
getTaskMetadata(taskType: string): string | null {
const taskInfo = this.taskInfos.find(t => t.taskType === taskType);
return taskInfo?.metadata || null;
}
hasMetadata(taskType: string): boolean {
const taskInfo = this.taskInfos.find(t => t.taskType === taskType);
return !!taskInfo?.metadata && taskInfo.metadata.trim().length > 0;
}
getMetadataIcon(taskType: string): string {
const icons: Record<string, string> = {
[TaskType.CLEAR_CBX_CACHE]: 'pi-database',
[TaskType.CLEAR_PDF_CACHE]: 'pi-database',
[TaskType.CLEANUP_DELETED_BOOKS]: 'pi-trash',
[TaskType.CLEANUP_TEMP_METADATA]: 'pi-file'
};
return icons[taskType] || 'pi-info-circle';
}
// ============================================================================
// UI Helper Methods - Task History & Status
// ============================================================================
getTaskHistory(taskType: string): TaskHistory | undefined {
return this.taskHistories.get(taskType);
}
getTaskProgressPercentage(taskType: string): number | null {
return this.taskHistories.get(taskType)?.progressPercentage || null;
}
getTaskUpdatedAt(taskType: string): string | null {
return this.taskHistories.get(taskType)?.updatedAt || null;
}
getTaskStatusMessage(taskType: string): string {
const history = this.taskHistories.get(taskType);
if (this.isTaskStale(history)) {
return 'Task appears to be stuck (no updates received)';
}
return history?.message || 'Processing...';
}
getLastRunMessage(taskType: string): string {
const history = this.taskHistories.get(taskType);
if (!history?.completedAt && !history?.updatedAt) {
return 'Never run';
}
const dateStr = history.completedAt || history.updatedAt;
if (!dateStr) return 'Never run';
const date = new Date(dateStr);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 1) return 'Just now';
if (diffMins < 60) return `${diffMins}m ago`;
if (diffHours < 24) return `${diffHours}h ago`;
if (diffDays < 7) return `${diffDays}d ago`;
return date.toLocaleDateString();
}
getLastRunInfoClass(taskType: string): string {
const history = this.taskHistories.get(taskType);
if (!history?.status) return 'info';
switch (history.status) {
case TaskStatus.COMPLETED:
return 'success';
case TaskStatus.FAILED:
return 'error';
case TaskStatus.CANCELLED:
return 'warning';
default:
return 'info';
}
}
// ============================================================================
// UI Helper Methods - Buttons & Icons
// ============================================================================
getTaskButtonIcon(taskType: string): string {
if (this.isTaskExecuting(taskType)) {
return 'pi pi-spinner pi-spin';
}
return 'pi ' + this.getTaskIcon(taskType);
}
getTaskButtonLabel(taskType: string): string {
const history = this.taskHistories.get(taskType);
if (this.isTaskStale(history)) {
return 'Re-run';
}
return 'Run';
}
getCancelButtonIcon(taskType: string): string {
if (this.isTaskExecuting(taskType)) {
return 'pi pi-spinner pi-spin';
}
return 'pi pi-times';
}
// ============================================================================
// UI Helper Methods - Metadata Replace
// ============================================================================
getMetadataReplaceDescription(mode: MetadataReplaceMode): string {
switch (mode) {
case MetadataReplaceMode.REPLACE_MISSING:
return 'Only update books that are missing metadata information. Existing metadata will be preserved.';
case MetadataReplaceMode.REPLACE_ALL:
return 'Replace all metadata for all books, even if they already have metadata. Use with caution as this will overwrite existing data.';
default:
return '';
}
}
// ============================================================================
// Utility Methods
// ============================================================================
formatDate(dateString: string): string {
const date = new Date(dateString);
return date.toLocaleString();
}
hasMetadata(task: Task): boolean {
return task.metadata && Object.keys(task.metadata).length > 0;
}
isTaskRunning(task: Task): boolean {
return task.status === TaskStatus.IN_PROGRESS || task.status === TaskStatus.PENDING;
}
isTaskStale(task: Task): boolean {
if (!task.updatedAt || !this.isTaskRunning(task)) {
return false;
}
const lastUpdate = new Date(task.updatedAt);
const now = new Date();
const timeDiff = now.getTime() - lastUpdate.getTime();
const minutesDiff = timeDiff / (1000 * 60);
return minutesDiff > 2;
}
getTaskStatusMessage(task: Task): string {
if (this.isTaskStale(task)) {
return 'Task appears to be stuck. You may need to cancel it.';
}
return task.message || 'Task is running...';
}
getLastRunInfoClass(status: string | null): string {
if (status === 'COMPLETED') return 'success';
if (status === 'FAILED') return 'error';
if (status === 'CANCELLED') return 'warning';
return 'info';
}
getLastRunMessage(task: Task): string {
const timeText = task.completedAt ? this.formatDate(task.completedAt) :
task.updatedAt ? this.formatDate(task.updatedAt) : '';
if (task.status === 'COMPLETED') {
return `Last completed: ${timeText}`;
} else if (task.status === 'FAILED') {
return `Failed: ${timeText}`;
} else if (task.status === 'CANCELLED') {
return `Cancelled: ${timeText}`;
}
return timeText ? `Last run: ${timeText}` : 'Not run yet';
}
getMetadataReplaceDescription(mode: MetadataReplaceMode): string {
const descriptions: Record<MetadataReplaceMode, string> = {
[MetadataReplaceMode.REPLACE_ALL]: 'Replace all existing metadata with data from files, even if metadata already exists in the database.',
[MetadataReplaceMode.REPLACE_MISSING]: 'Only update metadata that is missing or empty in the database, preserving existing metadata.'
};
return descriptions[mode];
}
private getTaskByType(type: string): Task {
return this.tasks.find(task => task.type === type) || {
id: null,
type,
status: null,
progressPercentage: null,
message: null,
createdAt: null,
updatedAt: null,
completedAt: null,
metadata: {}
};
}
private showMessage(severity: 'success' | 'info' | 'warn' | 'error', summary: string, detail: string): void {
this.messageService.add({
severity,
@@ -277,7 +593,4 @@ export class TaskManagementComponent implements OnInit, OnDestroy {
detail
});
}
protected readonly TaskType = TaskType;
protected readonly MetadataReplaceMode = MetadataReplaceMode;
}
@@ -7,15 +7,23 @@ import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refr
export enum TaskType {
CLEAR_CBX_CACHE = 'CLEAR_CBX_CACHE',
CLEAR_PDF_CACHE = 'CLEAR_PDF_CACHE',
RE_SCAN_LIBRARY = 'RE_SCAN_LIBRARY',
REFRESH_METADATA = 'REFRESH_METADATA',
REFRESH_LIBRARY_METADATA = 'REFRESH_LIBRARY_METADATA',
UPDATE_BOOK_RECOMMENDATIONS = 'UPDATE_BOOK_RECOMMENDATIONS',
CLEANUP_DELETED_BOOKS = 'CLEANUP_DELETED_BOOKS',
SYNC_LIBRARY_FILES = 'SYNC_LIBRARY_FILES',
CLEANUP_TEMP_METADATA = 'CLEANUP_TEMP_METADATA',
REFRESH_METADATA_MANUAL = 'REFRESH_METADATA_MANUAL'
}
export const TASK_TYPE_CONFIG: Record<TaskType, { parallel: boolean; async: boolean }> = {
[TaskType.CLEAR_CBX_CACHE]: {parallel: false, async: false},
[TaskType.CLEAR_PDF_CACHE]: {parallel: false, async: false},
[TaskType.RE_SCAN_LIBRARY]: {parallel: false, async: true},
[TaskType.REFRESH_METADATA]: {parallel: false, async: true}
export const TASK_TYPE_CONFIG: Record<TaskType, { parallel: boolean; async: boolean; displayOrder: number }> = {
[TaskType.REFRESH_LIBRARY_METADATA]: {parallel: false, async: true, displayOrder: 1},
[TaskType.SYNC_LIBRARY_FILES]: {parallel: false, async: false, displayOrder: 2},
[TaskType.UPDATE_BOOK_RECOMMENDATIONS]: {parallel: false, async: true, displayOrder: 3},
[TaskType.CLEANUP_DELETED_BOOKS]: {parallel: false, async: false, displayOrder: 4},
[TaskType.CLEANUP_TEMP_METADATA]: {parallel: false, async: false, displayOrder: 5},
[TaskType.REFRESH_METADATA_MANUAL]: {parallel: false, async: false, displayOrder: 6},
[TaskType.CLEAR_CBX_CACHE]: {parallel: false, async: false, displayOrder: 7},
[TaskType.CLEAR_PDF_CACHE]: {parallel: false, async: false, displayOrder: 8},
};
export enum MetadataReplaceMode {
@@ -41,7 +49,7 @@ export interface TaskCreateResponse {
}
export interface TaskStatusResponse {
tasks: Task[];
taskHistories: TaskHistory[];
}
export enum TaskStatus {
@@ -53,23 +61,36 @@ export enum TaskStatus {
PENDING = 'PENDING'
}
export interface TaskMetadata {
currentCacheSizeBytes?: number;
currentCacheSize?: string;
[key: string]: any;
export interface CronConfig {
id: number | null;
taskType: string;
cronExpression: string | null;
enabled: boolean;
options: Record<string, any> | null;
createdAt: string | null;
updatedAt: string | null;
}
export interface Task {
export interface TaskInfo {
taskType: string;
name: string;
description: string;
parallel: boolean;
async: boolean;
cronSupported: boolean;
cronConfig: CronConfig | null;
metadata?: string | null;
}
export interface TaskHistory {
id: string | null;
type: string;
status: string | null;
status: TaskStatus | null;
progressPercentage: number | null;
message: string | null;
createdAt: string | null;
updatedAt: string | null;
completedAt: string | null;
metadata: TaskMetadata;
}
export interface TaskCancelResponse {
@@ -78,6 +99,11 @@ export interface TaskCancelResponse {
message: string;
}
export interface TaskCronConfigRequest {
cronExpression?: string | null;
enabled?: boolean | null;
}
export interface TaskProgressPayload {
taskId: string;
taskType: string;
@@ -91,21 +117,29 @@ export interface TaskProgressPayload {
})
export class TaskService {
private http = inject(HttpClient);
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v2/tasks`;
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/tasks`;
private taskProgressSubject = new BehaviorSubject<TaskProgressPayload | null>(null);
public taskProgress$ = this.taskProgressSubject.asObservable();
getAvailableTasks(): Observable<TaskInfo[]> {
return this.http.get<TaskInfo[]>(`${this.baseUrl}`);
}
startTask(request: TaskCreateRequest): Observable<TaskCreateResponse> {
return this.http.post<TaskCreateResponse>(this.baseUrl, request);
return this.http.post<TaskCreateResponse>(`${this.baseUrl}/start`, request);
}
getLatestTasksForEachType(): Observable<TaskStatusResponse> {
return this.http.get<TaskStatusResponse>(`${this.baseUrl}/latest`);
return this.http.get<TaskStatusResponse>(`${this.baseUrl}/last`);
}
cancelTask(taskId: string): Observable<TaskCancelResponse> {
return this.http.delete<TaskCancelResponse>(`${this.baseUrl}/${taskId}`);
return this.http.delete<TaskCancelResponse>(`${this.baseUrl}/${taskId}/cancel`);
}
updateCronConfig(taskType: string, request: TaskCronConfigRequest): Observable<CronConfig> {
return this.http.patch<CronConfig>(`${this.baseUrl}/${taskType}/cron`, request);
}
handleTaskProgress(progress: TaskProgressPayload): void {