feat: mark messages missing from IMAP and stop queue retries

New missing_from_mailbox status for deleted UIDs; migration backfills existing fetch failures.
This commit is contained in:
1sonhador committed 2026-07-01 11:21:20 +01:00
1 parent 5b841a8850
commit 50b231caa6
10 files changed
+188 -7

No files matched your search

+9 -1
View File
@@ -2,14 +2,22 @@ const styles: Record<string, string> = {
pending: 'bg-yellow-100 text-yellow-800',
forwarded: 'bg-green-100 text-green-800',
failed: 'bg-red-100 text-red-800',
missing_from_mailbox: 'bg-gray-100 text-gray-700',
active: 'bg-green-100 text-green-800',
inactive: 'bg-gray-100 text-gray-600',
}
const labels: Record<string, string> = {
pending: 'pendente',
forwarded: 'reencaminhado',
failed: 'falhado',
missing_from_mailbox: 'apagado da mailbox',
}
export default function StatusBadge({ status }: { status: string }) {
return (
<span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${styles[status] ?? 'bg-gray-100 text-gray-700'}`}>
{status}
{labels[status] ?? status}
</span>
)
}
+3 -1
View File
@@ -57,7 +57,7 @@ export interface Message {
date: string
folder: string
created_at: string
status: 'pending' | 'forwarded' | 'failed'
status: 'pending' | 'forwarded' | 'failed' | 'missing_from_mailbox'
error: string | null
forwarded_at: string | null
}
@@ -96,6 +96,7 @@ export interface Stats {
messages_pending: number
messages_forwarded: number
messages_failed: number
messages_missing_from_mailbox?: number
last_sync_at: string | null
}
@@ -119,6 +120,7 @@ export interface SyncRunResult {
messages_forwarded: number
messages_skipped: number
messages_failed: number
messages_missing_from_mailbox?: number
error_message: string | null
started_at: string
finished_at: string | null
+1
View File
@@ -226,6 +226,7 @@ export default function Emails() {
<option value="pending">Pendente</option>
<option value="forwarded">Reencaminhado</option>
<option value="failed">Falhado</option>
<option value="missing_from_mailbox">Apagado da mailbox</option>
</select>
<button
onClick={reload}
@@ -0,0 +1,36 @@
"""Add missing_from_mailbox message status."""
from typing import Sequence, Union
from alembic import op
revision: str = "002_missing_from_mailbox"
down_revision: Union[str, None] = "001_initial"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.execute(
"ALTER TABLE messages MODIFY COLUMN status "
"ENUM('pending', 'forwarded', 'failed', 'skipped', 'dry_run', 'missing_from_mailbox') NOT NULL"
)
op.execute(
"""
UPDATE messages SET status = 'missing_from_mailbox'
WHERE status = 'failed' AND (
error_message LIKE 'Could not fetch message UID%%'
OR error_message LIKE 'Could not open folder:%%'
)
"""
)
def downgrade() -> None:
op.execute(
"UPDATE messages SET status = 'failed' WHERE status = 'missing_from_mailbox'"
)
op.execute(
"ALTER TABLE messages MODIFY COLUMN status "
"ENUM('pending', 'forwarded', 'failed', 'skipped', 'dry_run') NOT NULL"
)
+12 -1
View File
@@ -12,7 +12,10 @@ from forwarder.services.forward_queue_service import (
requeue_forwarded_messages,
)
from forwarder.email.parsing import parse_email_datetime
from forwarder.services.sync_service import retry_single_message
from forwarder.services.sync_service import (
MessageMissingFromMailboxError,
retry_single_message,
)
from forwarder.services.rate_limit import ForwardRateLimitError
router = APIRouter(prefix="/messages", tags=["messages"])
@@ -167,8 +170,16 @@ def retry_message(
if account is None:
raise HTTPException(status_code=404, detail="Account not found")
if message.status == MessageStatus.missing_from_mailbox:
raise HTTPException(
status_code=410,
detail=message.error_message or "Message no longer in mailbox",
)
try:
updated = retry_single_message(db, message_id)
except MessageMissingFromMailboxError as exc:
raise HTTPException(status_code=410, detail=str(exc)) from exc
except ForwardRateLimitError as exc:
raise HTTPException(status_code=429, detail=str(exc)) from exc
except ValueError as exc:
+8
View File
@@ -19,6 +19,7 @@ class StatsResponse(BaseModel):
messages_pending: int
messages_forwarded: int
messages_failed: int
messages_missing_from_mailbox: int
last_sync_at: datetime | None = None
@@ -47,6 +48,12 @@ def get_stats(db: DbSession, _user: CurrentUser) -> StatsResponse:
.scalar()
or 0
)
messages_missing_from_mailbox = (
db.query(func.count(Message.id))
.filter(Message.status == MessageStatus.missing_from_mailbox)
.scalar()
or 0
)
last_run = db.query(SyncRun.started_at).order_by(SyncRun.id.desc()).first()
last_sync_at = last_run[0] if last_run else None
@@ -57,5 +64,6 @@ def get_stats(db: DbSession, _user: CurrentUser) -> StatsResponse:
messages_pending=messages_pending,
messages_forwarded=messages_forwarded,
messages_failed=messages_failed,
messages_missing_from_mailbox=messages_missing_from_mailbox,
last_sync_at=last_sync_at,
)
+1
View File
@@ -29,6 +29,7 @@ class MessageStatus(str, enum.Enum):
failed = "failed"
skipped = "skipped"
dry_run = "dry_run"
missing_from_mailbox = "missing_from_mailbox"
class SyncRunStatus(str, enum.Enum):
@@ -15,7 +15,10 @@ from forwarder.services.rate_limit import (
count_forwards_last_hour,
forwards_remaining_this_hour,
)
from forwarder.services.sync_service import retry_single_message
from forwarder.services.sync_service import (
MessageMissingFromMailboxError,
retry_single_message,
)
logger = logging.getLogger(__name__)
@@ -114,6 +117,8 @@ def process_forward_queue(db: Session) -> ForwardQueueResult:
check_forward_allowed(db)
retry_single_message(db, message.id)
result.succeeded += 1
except MessageMissingFromMailboxError as exc:
logger.info("Message %s no longer in mailbox: %s", message.id, exc)
except ForwardRateLimitError:
result.rate_limited = True
logger.info("Forward queue paused: hourly limit reached")
+54 -3
View File
@@ -37,6 +37,20 @@ from forwarder.services.rate_limit import ForwardRateLimitError, check_forward_a
logger = logging.getLogger(__name__)
class MessageMissingFromMailboxError(Exception):
"""The message record exists but the email is no longer on IMAP."""
def __init__(self, message: Message, reason: str) -> None:
self.message = message
super().__init__(reason)
def is_missing_from_mailbox_error(error_text: str) -> bool:
return error_text.startswith("Could not fetch message UID") or error_text.startswith(
"Could not open folder:"
)
class SyncResult:
def __init__(self) -> None:
self.messages_scanned = 0
@@ -352,7 +366,24 @@ def sync_account(
db.commit()
db.refresh(sync_run)
return sync_run
return msg
def _mark_missing_from_mailbox(db: Session, message: Message, reason: str) -> Message:
message.status = MessageStatus.missing_from_mailbox
message.error_message = reason
message.updated_at = datetime.now(timezone.utc)
_record_forward_attempt(
db,
message=message,
success=False,
dry_run=False,
error_message=reason,
)
db.commit()
db.refresh(message)
logger.info("Message %s missing from mailbox: %s", message.id, reason)
return message
def retry_single_message(db: Session, message_id: int) -> Message:
@@ -361,6 +392,11 @@ def retry_single_message(db: Session, message_id: int) -> Message:
raise ValueError(f"Message {message_id} not found")
if message.status == MessageStatus.forwarded:
raise ValueError("Message already forwarded")
if message.status == MessageStatus.missing_from_mailbox:
raise MessageMissingFromMailboxError(
message,
message.error_message or "Message no longer in mailbox",
)
account = get_account(db, message.account_id)
imap_config = ImapConfig(
@@ -382,12 +418,22 @@ def retry_single_message(db: Session, message_id: int) -> Message:
try:
imap = connect_imap(imap_config)
if not select_folder_readonly(imap, message.folder):
raise ValueError(f"Could not open folder: {message.folder}")
marked = _mark_missing_from_mailbox(
db,
message,
f"Could not open folder: {message.folder}",
)
raise MessageMissingFromMailboxError(marked, marked.error_message or "")
uid_bytes = message.uid.encode() if isinstance(message.uid, str) else message.uid
msg = fetch_message(imap, uid_bytes)
if msg is None:
raise ValueError(f"Could not fetch message UID {message.uid}")
marked = _mark_missing_from_mailbox(
db,
message,
f"Could not fetch message UID {message.uid}",
)
raise MessageMissingFromMailboxError(marked, marked.error_message or "")
smtp = create_smtp_client(smtp_config)
allowed_extensions = set(account.allowed_extensions or [])
@@ -409,8 +455,13 @@ def retry_single_message(db: Session, message_id: int) -> Message:
db.refresh(message)
logger.info("Retry forwarded: %s", message.subject)
return message
except MessageMissingFromMailboxError:
raise
except Exception as exc:
error_text = str(exc)
if is_missing_from_mailbox_error(error_text):
marked = _mark_missing_from_mailbox(db, message, error_text)
raise MessageMissingFromMailboxError(marked, error_text) from exc
message.status = MessageStatus.failed
message.error_message = error_text
message.updated_at = datetime.now(timezone.utc)
+58
View File
@@ -0,0 +1,58 @@
"""Tests for missing-from-mailbox handling."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import pytest
from forwarder.db.models import MessageStatus
from forwarder.services.sync_service import (
MessageMissingFromMailboxError,
is_missing_from_mailbox_error,
retry_single_message,
)
def test_is_missing_from_mailbox_error():
assert is_missing_from_mailbox_error("Could not fetch message UID 5480")
assert is_missing_from_mailbox_error("Could not open folder: INBOX.old")
assert not is_missing_from_mailbox_error("SMTP timeout")
def test_retry_marks_missing_when_uid_not_found():
db = MagicMock()
message = MagicMock()
message.id = 1
message.account_id = 2
message.status = MessageStatus.failed
message.folder = "INBOX"
message.uid = "5480"
message.subject = "Test"
db.get.return_value = message
account = MagicMock()
imap = MagicMock()
with patch("forwarder.services.sync_service.get_account", return_value=account):
with patch("forwarder.services.sync_service.decrypt_password", return_value="secret"):
with patch("forwarder.services.sync_service.connect_imap", return_value=imap):
with patch("forwarder.services.sync_service.select_folder_readonly", return_value=True):
with patch("forwarder.services.sync_service.fetch_message", return_value=None):
with patch("forwarder.services.sync_service._record_forward_attempt"):
with pytest.raises(MessageMissingFromMailboxError) as exc:
retry_single_message(db, 1)
assert message.status == MessageStatus.missing_from_mailbox
assert "5480" in str(exc.value)
def test_retry_skips_already_missing():
db = MagicMock()
message = MagicMock()
message.status = MessageStatus.missing_from_mailbox
message.error_message = "gone"
db.get.return_value = message
with pytest.raises(MessageMissingFromMailboxError):
retry_single_message(db, 99)