From 379d54bc9d225d60deed929b97bfe5969c17fa1c Mon Sep 17 00:00:00 2001 From: rustmailer Date: Fri, 16 Oct 2026 07:30:50 +0800 Subject: [PATCH] feat: manually retry failed tasks in the task queue (#30) --- env/rustmailer.env | 3 + src/modules/rest/api/mod.rs | 15 +++ src/modules/rest/api/send.rs | 84 +++++++++++- src/modules/scheduler/nativedb/meta.rs | 110 ++++++++++++++- src/modules/scheduler/tests.rs | 127 +++++++++++++++++- src/modules/settings/cli.rs | 30 +++++ src/modules/tasks/queue.rs | 16 +++ web/src/api/tasks/api.ts | 16 +++ .../tasks/components/data-table-toolbar.tsx | 16 ++- .../components/email-table-row-actions.tsx | 43 +++++- .../features/tasks/components/email-table.tsx | 7 + .../components/retry-failed-tasks-dialog.tsx | 76 +++++++++++ 12 files changed, 537 insertions(+), 6 deletions(-) create mode 100644 web/src/features/tasks/components/retry-failed-tasks-dialog.tsx diff --git a/env/rustmailer.env b/env/rustmailer.env index c1dedfd..bc87928 100644 --- a/env/rustmailer.env +++ b/env/rustmailer.env @@ -79,6 +79,9 @@ RUSTMAILER_MAX_EMAIL_CONTENT_LENGTH=10000 # Cleanup task run interval (in hours) RUSTMAILER_CLEANUP_INTERVAL_HOURS=72 +# How long (in hours) failed tasks are kept so they can be manually retried +RUSTMAILER_FAILED_TASK_RETENTION_HOURS=168 + # Directory to store backup files (leave empty to disable backups) RUSTMAILER_BACKUP_DIR= diff --git a/src/modules/rest/api/mod.rs b/src/modules/rest/api/mod.rs index ae1b662..a639cdd 100644 --- a/src/modules/rest/api/mod.rs +++ b/src/modules/rest/api/mod.rs @@ -82,3 +82,18 @@ pub fn create_openapi_service() -> OpenApiService { rustmailer_version!(), ) } + +#[cfg(test)] +mod tests { + use super::*; + + /// Duplicate `operation_id`s and malformed paths only surface when the + /// OpenAPI document is generated (the duplicate case panics), so building + /// the document is the cheapest way to guard the whole API surface. + #[test] + fn openapi_document_builds() { + let spec = create_openapi_service().spec(); + assert!(spec.contains("/api/v1/send-email-task/{id}/retry")); + assert!(spec.contains("/api/v1/send-email-tasks/retry")); + } +} diff --git a/src/modules/rest/api/send.rs b/src/modules/rest/api/send.rs index 2a25936..b72d809 100644 --- a/src/modules/rest/api/send.rs +++ b/src/modules/rest/api/send.rs @@ -22,9 +22,19 @@ use std::collections::BTreeSet; use poem_openapi::param::Query; use poem_openapi::payload::Json; -use poem_openapi::OpenApi; +use poem_openapi::{Object, OpenApi}; +use serde::{Deserialize, Serialize}; + pub struct SendMailApi; +/// The outcome of a batch retry request. +#[derive(Debug, Clone, Serialize, Deserialize, Object)] +pub struct RetryTasksResult { + /// The number of tasks that were actually requeued. Tasks that had already + /// been retried or removed in the meantime are not counted. + pub retried: usize, +} + #[OpenApi(prefix_path = "/api/v1", tag = "ApiTags::SendMail")] impl SendMailApi { /// Sends a new email for a specified account. @@ -257,4 +267,76 @@ impl SendMailApi { context.require_account_access(task.account_id)?; Ok(send_queue.remove_task(id).await?) } + + /// Retries a failed email task. + /// The task is requeued with its original request data, so the email body is + /// reloaded from the disk cache and there is no need to resubmit the original + /// send request. Only tasks that failed or were stopped can be retried. + #[oai( + path = "/send-email-task/:id/retry", + method = "post", + operation_id = "retry_email_task" + )] + async fn retry_email_task( + &self, + /// The ID of the email task to retry + id: Path, + context: ClientContext, + ) -> ApiResult<()> { + let send_queue = RustMailerTaskQueue::get().unwrap(); + let id = id.0; + let task = send_queue + .get_email_task(id) + .await? + .ok_or_else(|| raise_error!("Task not found".into(), ErrorCode::ResourceNotFound))?; + + context.require_account_access(task.account_id)?; + Ok(send_queue.retry_email_task(id).await?) + } + + /// Retries every failed email task, optionally restricted to a time window. + /// This is meant for recovering after a mail server outage or migration: the + /// failed tasks are requeued as they are, so nothing has to be recreated. + /// Only tasks in the `Failed` state are retried; pass a `created_after` and/or + /// `created_before` bound (Unix timestamp in milliseconds) to narrow the set. + #[oai( + path = "/send-email-tasks/retry", + method = "post", + operation_id = "retry_email_tasks" + )] + async fn retry_email_tasks( + &self, + /// Optional. Only retry tasks created at or after this Unix timestamp (milliseconds). + created_after: Query>, + /// Optional. Only retry tasks created at or before this Unix timestamp (milliseconds). + created_before: Query>, + context: ClientContext, + ) -> ApiResult> { + let send_queue = RustMailerTaskQueue::get().unwrap(); + + // Non-root callers only see the accounts their token grants access to. + let allowed_ids: Option> = context + .accessible_accounts()? + .map(|accounts| accounts.iter().map(|a| a.id).collect()); + + let ids: Vec = send_queue + .list_email_tasks_by_status(TaskStatus::Failed) + .await? + .into_iter() + .filter(|task| { + let time_match = created_after.0.map_or(true, |after| task.created_at >= after) + && created_before + .0 + .map_or(true, |before| task.created_at <= before); + let account_match = allowed_ids + .as_ref() + .map_or(true, |allowed| allowed.contains(&task.account_id)); + time_match && account_match + }) + .map(|task| task.id) + .collect(); + + let retried = send_queue.retry_email_tasks(ids).await?; + Ok(Json(RetryTasksResult { retried })) + } } diff --git a/src/modules/scheduler/nativedb/meta.rs b/src/modules/scheduler/nativedb/meta.rs index cacb323..b46a3f4 100644 --- a/src/modules/scheduler/nativedb/meta.rs +++ b/src/modules/scheduler/nativedb/meta.rs @@ -169,9 +169,17 @@ impl NativeDbTaskStore { let cleanup_interval_ms = SETTINGS.rustmailer_cleanup_interval_hours as i64 * HOUR_TO_MS as i64; + // Failed tasks are retained longer than the other terminal states so that + // they can still be inspected and manually retried after an outage. + let failed_retention_ms = + SETTINGS.rustmailer_failed_task_retention_hours as i64 * HOUR_TO_MS as i64; let now = utc_now!(); for status in statuses_to_clean { + let retention_ms = match status { + TaskStatus::Failed => failed_retention_ms, + _ => cleanup_interval_ms, + }; // let status_str = status.to_string(); let task_ids: Vec = { let rw = database @@ -183,7 +191,7 @@ impl NativeDbTaskStore { .start_with(status.code()) .map_err(|e| raise_error!(format!("{:#?}", e), ErrorCode::InternalError))? .filter_map(|result| match result { - Ok(t) if now - t.created_at > cleanup_interval_ms => Some(Ok(t.id)), + Ok(t) if now - t.created_at > retention_ms => Some(Ok(t.id)), Ok(_) => None, Err(e) => Some(Err(e)), }) @@ -251,6 +259,106 @@ impl NativeDbTaskStore { Ok(()) } + /// Returns `true` when a task in this state may be manually retried. + /// + /// Only terminal states that still represent an attempt worth repeating are + /// retryable. In particular `Scheduled`/`Running` are excluded so a manual + /// retry can never race with the scheduler. + fn is_retryable(status: &TaskStatus) -> bool { + matches!(status, TaskStatus::Failed | TaskStatus::Stopped) + } + + /// Clears the terminal state of a task so the scheduler picks it up again on + /// its next tick: the retry counter is reset (handing the task a full + /// automatic retry budget again) and `next_run` is pulled forward to now. + fn rewind_for_retry(entity: &TaskMetaEntity) -> TaskMetaEntity { + let mut updated = entity.clone(); + updated.status = TaskStatus::Scheduled; + updated.retry_count = None; + updated.last_error = None; + updated.stopped_reason = None; + updated.next_run = utc_now!(); + updated.updated_at = utc_now!(); + updated + } + + /// Rewinds a single task so it is executed again. + /// + /// Fails with `InvalidParameter` when the task exists but is not in a + /// retryable state, and with `ResourceNotFound` when it does not exist. + pub async fn reset_for_retry( + database: &Arc>, + task_id: u64, + ) -> RustMailerResult<()> { + update_impl( + database, + move |rw| { + rw.get() + .secondary::(TaskMetaEntityKey::id, task_id) + .map_err(|e| raise_error!(format!("{:#?}", e), ErrorCode::InternalError))? + .ok_or_else(|| { + raise_error!( + format!("The task with id={} was not found.", task_id), + ErrorCode::ResourceNotFound + ) + }) + }, + |current| { + if !Self::is_retryable(¤t.status) { + return Err(raise_error!( + format!( + "The task with id={} is in state '{}' and cannot be retried. Only failed or stopped tasks can be retried.", + current.id, current.status + ), + ErrorCode::InvalidParameter + )); + } + Ok(Self::rewind_for_retry(current)) + }, + ) + .await?; + Ok(()) + } + + /// Rewinds a batch of tasks and returns how many were actually requeued. + /// + /// Unknown ids and ids that are not in a retryable state are skipped, so a + /// batch retry is safe to fire at a list that changed in the meantime. + pub async fn reset_tasks_for_retry( + database: &Arc>, + task_ids: Vec, + ) -> RustMailerResult { + if task_ids.is_empty() { + return Ok(0); + } + let updated = batch_update_impl( + database, + move |rw| { + let mut retryable = Vec::new(); + for task_id in task_ids.iter() { + let entity = rw + .get() + .secondary::(TaskMetaEntityKey::id, *task_id) + .map_err(|e| raise_error!(format!("{:#?}", e), ErrorCode::InternalError))?; + if let Some(entity) = entity { + if Self::is_retryable(&entity.status) { + retryable.push(entity); + } + } + } + Ok(retryable) + }, + |targets| { + Ok(targets + .iter() + .map(|entity| (entity.clone(), Self::rewind_for_retry(entity))) + .collect::>()) + }, + ) + .await?; + Ok(updated.len()) + } + pub async fn heartbeat( database: &Arc>, task_id: u64, diff --git a/src/modules/scheduler/tests.rs b/src/modules/scheduler/tests.rs index c17993c..8694334 100644 --- a/src/modules/scheduler/tests.rs +++ b/src/modules/scheduler/tests.rs @@ -10,10 +10,12 @@ use serde::{Deserialize, Serialize}; use crate::{ generate_token, modules::{ - error::code::ErrorCode, + error::{code::ErrorCode, RustMailerError}, scheduler::{ context::TaskContext, + model::{TaskMeta, TaskStatus}, nativedb::{meta::NativeDbTaskStore, TASK_MODELS}, + retry::{RetryPolicy, RetryStrategy}, }, }, raise_error, @@ -21,6 +23,129 @@ use crate::{ use super::task::Task; +/// Builds a stored-shape task sitting in the given terminal (or non-terminal) +/// state, as if a previous delivery attempt had just given up. +fn task_in_state(status: TaskStatus) -> TaskMeta { + let mut meta = TaskMeta::new( + "retry_test_task_key".to_string(), + "{}".to_string(), + "retry_test_queue".to_string(), + RetryPolicy { + strategy: RetryStrategy::Linear { interval: 1 }, + max_retries: Some(3), + }, + 0, + ); + meta.status = status; + meta.retry_count = Some(3); + meta.last_error = Some("smtp connection refused".to_string()); + meta.next_run = 0; + meta +} + +#[tokio::test] +async fn reset_for_retry_requeues_a_failed_task() { + let db = Arc::new(Builder::new().create_in_memory(&TASK_MODELS).unwrap()); + let failed = task_in_state(TaskStatus::Failed); + let id = failed.id; + NativeDbTaskStore::store_one(&db, failed).await.unwrap(); + + NativeDbTaskStore::reset_for_retry(&db, id).await.unwrap(); + + let requeued = NativeDbTaskStore::get(&db, id).await.unwrap().unwrap(); + assert_eq!(requeued.status, TaskStatus::Scheduled); + // The retry counter is cleared so the task gets a full automatic retry + // budget again, and the stale error is dropped. + assert_eq!(requeued.retry_count, None); + assert_eq!(requeued.last_error, None); + // `next_run` is pulled forward so the scheduler picks the task up on its + // next tick rather than keeping the stale timestamp. + assert!(requeued.next_run > 0); +} + +#[tokio::test] +async fn reset_for_retry_rejects_a_task_that_is_not_terminal() { + let db = Arc::new(Builder::new().create_in_memory(&TASK_MODELS).unwrap()); + let scheduled = task_in_state(TaskStatus::Scheduled); + let id = scheduled.id; + NativeDbTaskStore::store_one(&db, scheduled).await.unwrap(); + + let err = NativeDbTaskStore::reset_for_retry(&db, id) + .await + .unwrap_err(); + match err { + RustMailerError::Generic { code, .. } => assert_eq!(code, ErrorCode::InvalidParameter), + } + // The rejected task is left exactly as it was. + let untouched = NativeDbTaskStore::get(&db, id).await.unwrap().unwrap(); + assert_eq!(untouched.status, TaskStatus::Scheduled); + assert_eq!(untouched.retry_count, Some(3)); +} + +/// The whole point of a manual retry is that the scheduler picks the task up +/// again, which depends on the fetch scan matching the reset status *and* the +/// rewritten `next_run`. Assert it end to end rather than trusting the fields. +#[tokio::test] +async fn a_retried_task_is_picked_up_by_the_scheduler_scan() { + let db = Arc::new(Builder::new().create_in_memory(&TASK_MODELS).unwrap()); + let failed = task_in_state(TaskStatus::Failed); + let id = failed.id; + NativeDbTaskStore::store_one(&db, failed).await.unwrap(); + + // A failed task is invisible to the fetch loop... + assert!(NativeDbTaskStore::fetch_pending_tasks(&db) + .await + .unwrap() + .is_empty()); + + NativeDbTaskStore::reset_for_retry(&db, id).await.unwrap(); + + // ...but a retried one is handed to a worker on the next tick. + let pending = NativeDbTaskStore::fetch_pending_tasks(&db).await.unwrap(); + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].id, id); + + // The fetch hands back a pre-claim snapshot of each task, so the status on + // the returned value is the old one; what matters is that the store itself + // has already claimed the task as `Running`. + let claimed = NativeDbTaskStore::get(&db, id).await.unwrap().unwrap(); + assert_eq!(claimed.status, TaskStatus::Running); + + // ...which also means it is not dispatched a second time. + assert!(NativeDbTaskStore::fetch_pending_tasks(&db) + .await + .unwrap() + .is_empty()); +} + +#[tokio::test] +async fn reset_tasks_for_retry_skips_unknown_and_unretryable_ids() { + let db = Arc::new(Builder::new().create_in_memory(&TASK_MODELS).unwrap()); + let failed = task_in_state(TaskStatus::Failed); + let succeeded = task_in_state(TaskStatus::Success); + let failed_id = failed.id; + let succeeded_id = succeeded.id; + NativeDbTaskStore::store_one(&db, failed).await.unwrap(); + NativeDbTaskStore::store_one(&db, succeeded).await.unwrap(); + + let retried = + NativeDbTaskStore::reset_tasks_for_retry(&db, vec![failed_id, succeeded_id, u64::MAX]) + .await + .unwrap(); + + assert_eq!(retried, 1); + let requeued = NativeDbTaskStore::get(&db, failed_id) + .await + .unwrap() + .unwrap(); + assert_eq!(requeued.status, TaskStatus::Scheduled); + let untouched = NativeDbTaskStore::get(&db, succeeded_id) + .await + .unwrap() + .unwrap(); + assert_eq!(untouched.status, TaskStatus::Success); +} + #[derive(Debug, Clone, Serialize, Deserialize)] struct RetryTestTask; diff --git a/src/modules/settings/cli.rs b/src/modules/settings/cli.rs index 688f579..429d911 100644 --- a/src/modules/settings/cli.rs +++ b/src/modules/settings/cli.rs @@ -325,6 +325,35 @@ pub struct Settings { )] pub rustmailer_cleanup_interval_hours: u64, + #[clap( + long, + default_value = "168", + env, + help = "How long (in hours) failed tasks are retained so they can be manually retried. Failed tasks older than this duration are removed during cleanup.", + value_parser = ValueParser::new(|s: &str| { + // Parse the string to a u64 + let value = s.parse::().map_err(|_| { + format!( + "Invalid value: {}. Please provide a valid number of hours.", + s + ) + })?; + + // Set min and max limits + if value < 1 { + return Err("Failed task retention must be at least 1 hour.".to_string()); + } + if value > 8760 { + return Err( + "Failed task retention must be at most 8760 hours (365 days).".to_string() + ); + } + + Ok(value) + }) + )] + pub rustmailer_failed_task_retention_hours: u64, + #[clap( long, help = "Set the directory for storing backups of meta.db and tasks.db (must exist and have read/write permissions)", @@ -479,6 +508,7 @@ impl Settings { rustmailer_event_hook_workers: 10, rustmailer_max_email_content_length: 10000, rustmailer_cleanup_interval_hours: 72, + rustmailer_failed_task_retention_hours: 168, rustmailer_backup_dir: None, rustmailer_max_backups: 10, rustmailer_email_tracking_url: "http://localhost:15630/email-track".to_string(), diff --git a/src/modules/tasks/queue.rs b/src/modules/tasks/queue.rs index 18458e5..78c327c 100644 --- a/src/modules/tasks/queue.rs +++ b/src/modules/tasks/queue.rs @@ -291,4 +291,20 @@ impl RustMailerTaskQueue { pub async fn remove_task(&self, id: u64) -> RustMailerResult<()> { NativeDbTaskStore::set_status(DB_MANAGER.tasks_db(), id, TaskStatus::Removed, None).await } + + /// Requeues a single failed email task so the scheduler sends it again. + /// + /// The task keeps its original parameters, so the email body is reloaded + /// from the disk cache and nothing has to be resubmitted by the caller. + pub async fn retry_email_task(&self, id: u64) -> RustMailerResult<()> { + NativeDbTaskStore::reset_for_retry(DB_MANAGER.tasks_db(), id).await + } + + /// Requeues several email tasks at once and returns how many were requeued. + /// + /// Ids that are unknown or no longer retryable are skipped rather than + /// failing the whole batch. + pub async fn retry_email_tasks(&self, ids: Vec) -> RustMailerResult { + NativeDbTaskStore::reset_tasks_for_retry(DB_MANAGER.tasks_db(), ids).await + } } diff --git a/web/src/api/tasks/api.ts b/web/src/api/tasks/api.ts index 0d59a3b..327346b 100644 --- a/web/src/api/tasks/api.ts +++ b/web/src/api/tasks/api.ts @@ -20,6 +20,22 @@ export const delete_email_task = async (id: number) => { return response.data; } +export const retry_email_task = async (id: number) => { + const response = await axiosInstance.post(`/api/v1/send-email-task/${id}/retry`); + return response.data; +} + +export const retry_email_tasks = async (created_after?: number, created_before?: number) => { + const params = new URLSearchParams(); + if (created_after !== undefined) params.append('created_after', `${created_after}`); + if (created_before !== undefined) params.append('created_before', `${created_before}`); + const query = params.toString(); + const response = await axiosInstance.post<{ retried: number }>( + `/api/v1/send-email-tasks/retry${query ? `?${query}` : ''}` + ); + return response.data; +} + export const list_hook_tasks = async (pageIndex: number, pageSize: number, status: TaskStatus | 'all') => { const baseUrl = `/api/v1/hook-tasks?page=${pageIndex + 1}&page_size=${pageSize}&desc=true`; const url = status !== 'all' ? `${baseUrl}&status=${status}` : baseUrl; diff --git a/web/src/features/tasks/components/data-table-toolbar.tsx b/web/src/features/tasks/components/data-table-toolbar.tsx index 0b64d7d..b0c39b4 100644 --- a/web/src/features/tasks/components/data-table-toolbar.tsx +++ b/web/src/features/tasks/components/data-table-toolbar.tsx @@ -5,6 +5,7 @@ */ import { Table } from '@tanstack/react-table' +import { IconRefresh } from '@tabler/icons-react' import { Input } from '@/components/ui/input' import { Button } from '@/components/ui/button' import { TaskStatus } from '../data/schema' @@ -14,6 +15,7 @@ interface DataTableToolbarProps { placeHolder: string statusFilter?: TaskStatus | 'all' onStatusFilterChange: (status: TaskStatus | 'all') => void + onRetryAllFailed?: () => void } const statusOptions = [ @@ -30,7 +32,8 @@ export function DataTableToolbar({ table, placeHolder, statusFilter = 'all', - onStatusFilterChange + onStatusFilterChange, + onRetryAllFailed }: DataTableToolbarProps) { return (
@@ -57,6 +60,17 @@ export function DataTableToolbar({ ))}
+ {onRetryAllFailed && ( + + )} ) } \ No newline at end of file diff --git a/web/src/features/tasks/components/email-table-row-actions.tsx b/web/src/features/tasks/components/email-table-row-actions.tsx index 69b845f..275b31d 100644 --- a/web/src/features/tasks/components/email-table-row-actions.tsx +++ b/web/src/features/tasks/components/email-table-row-actions.tsx @@ -6,7 +6,7 @@ import { DotsHorizontalIcon } from '@radix-ui/react-icons' import { Row } from '@tanstack/react-table' -import { IconTrash } from '@tabler/icons-react' +import { IconRefresh, IconTrash } from '@tabler/icons-react' import { Button } from '@/components/ui/button' import { DropdownMenu, @@ -17,8 +17,11 @@ import { DropdownMenuTrigger, } from '@/components/ui/dropdown-menu' import { useTasksContext } from '../context' -import { EmailTask } from '../data/schema' +import { EmailTask, TaskStatus } from '../data/schema' import { MessageSquareMore } from 'lucide-react' +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { toast } from '@/hooks/use-toast' +import { retry_email_task } from '@/api/tasks/api' interface EmailTableRowActionsProps { row: Row @@ -26,6 +29,31 @@ interface EmailTableRowActionsProps { export function EmailTableRowActions({ row }: EmailTableRowActionsProps) { const { setOpen, setCurrentEmailRow } = useTasksContext() + const queryClient = useQueryClient() + + const retryMutation = useMutation({ + mutationFn: () => retry_email_task(row.original.id), + retry: 0, + onSuccess: () => { + toast({ + title: 'Task requeued', + description: `Task ${row.original.id} will be sent again.`, + }) + queryClient.invalidateQueries({ queryKey: ['send-email-tasks'] }) + }, + onError: (error: Error) => { + toast({ + title: 'Failed to retry task', + description: `${error.message}`, + variant: 'destructive', + }) + }, + }) + + const retryable = + row.original.status === TaskStatus.Failed || + row.original.status === TaskStatus.Stopped + return ( <> @@ -50,6 +78,17 @@ export function EmailTableRowActions({ row }: EmailTableRowActionsProps) { + {retryable && ( + retryMutation.mutate()} + > + Retry + + + + + )} { diff --git a/web/src/features/tasks/components/email-table.tsx b/web/src/features/tasks/components/email-table.tsx index ffc100a..e2569f9 100644 --- a/web/src/features/tasks/components/email-table.tsx +++ b/web/src/features/tasks/components/email-table.tsx @@ -30,6 +30,7 @@ import { import { EmailTask, TaskStatus } from '../data/schema' import { DataTablePagination } from './data-table-pagination' import { DataTableToolbar } from './data-table-toolbar' +import { RetryFailedTasksDialog } from './retry-failed-tasks-dialog' import { useQuery } from '@tanstack/react-query' import Logo from '@/assets/logo.svg' import { TableSkeleton } from '@/components/table-skeleton' @@ -56,6 +57,7 @@ export function EmailTaskTable({ columns }: DataTableProps) { pageSize: 10, }); const [statusFilter, setStatusFilter] = useState('all'); + const [retryDialogOpen, setRetryDialogOpen] = useState(false); const { data: queryResult, isLoading } = useQuery({ queryKey: ['send-email-tasks', pagination.pageIndex, pagination.pageSize, statusFilter], @@ -119,6 +121,11 @@ export function EmailTaskTable({ columns }: DataTableProps) { placeHolder="Filter email tasks..." statusFilter={statusFilter} onStatusFilterChange={handleStatusFilterChange} + onRetryAllFailed={() => setRetryDialogOpen(true)} + /> + {isLoading ? ( diff --git a/web/src/features/tasks/components/retry-failed-tasks-dialog.tsx b/web/src/features/tasks/components/retry-failed-tasks-dialog.tsx new file mode 100644 index 0000000..11e982b --- /dev/null +++ b/web/src/features/tasks/components/retry-failed-tasks-dialog.tsx @@ -0,0 +1,76 @@ +/* + * Copyright © 2025-2026 rustmailer.com + * Licensed under RustMailer License Agreement v1.0 + * Unauthorized use or distribution is prohibited. + */ + +import { IconRefresh } from '@tabler/icons-react' +import { toast } from '@/hooks/use-toast' +import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert' +import { ConfirmDialog } from '@/components/confirm-dialog' +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { retry_email_tasks } from '@/api/tasks/api' + +interface Props { + open: boolean + onOpenChange: (open: boolean) => void +} + +export function RetryFailedTasksDialog({ open, onOpenChange }: Props) { + const queryClient = useQueryClient() + const retryMutation = useMutation({ + mutationFn: () => retry_email_tasks(), + retry: 0, + onSuccess: (result) => { + toast({ + title: 'Failed tasks requeued', + description: + result.retried > 0 + ? `${result.retried} task${result.retried === 1 ? '' : 's'} will be sent again.` + : 'There were no failed tasks to retry.', + }) + queryClient.invalidateQueries({ queryKey: ['send-email-tasks'] }) + onOpenChange(false) + }, + onError: (error: Error) => { + toast({ + title: 'Failed to retry tasks', + description: `${error.message}`, + variant: 'destructive', + }) + }, + }) + + return ( + retryMutation.mutate()} + isLoading={retryMutation.isPending} + className='max-w-2xl' + title={ + + Retry All Failed Tasks + + } + desc={ +
+

+ Every email task currently in the{' '} + Failed state will be requeued and + sent again. The tasks keep their original request data, so there is + no need to resend the original requests. +

+ + Heads up + + Retried emails are loaded from the local email cache. Tasks whose + cached content has already been evicted will fail again. + + +
+ } + confirmText='Retry' + /> + ) +}