fix(imap): catch TimeoutError on per-message fetch so sync continues (BIT-33891) #8

Merged
spark merged 1 commits from fix/BIT-33891-imap-timeout into main 2026-12-03 23:31:18 +00:00
2 changed files with 55 additions and 1 deletions

No files matched your search

+1 -1
View File
@@ -260,7 +260,7 @@ def sync_account(
try:
msg = fetch_message(imap, uid)
except imaplib.IMAP4.error as exc:
except (imaplib.IMAP4.error, OSError) as exc:
logger.error("Fetch error UID %s in %s: %s", uid_str, folder, exc)
result.messages_failed += 1
continue
+54
View File
@@ -0,0 +1,54 @@
"""Tests for IMAP timeout handling in sync_account."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from forwarder.db.models import DeliveryMode, SourceType, SyncRunStatus
from forwarder.services.sync_service import sync_account
def _make_account() -> MagicMock:
account = MagicMock()
account.source_type = SourceType.imap
account.imap_host = "imap.example.com"
account.imap_port = 993
account.imap_user = "[email protected]"
account.imap_password_encrypted = b"encrypted"
account.delivery_mode = DeliveryMode.api
account.bizdocs_password_encrypted = b"encrypted"
account.allowed_extensions = None
account.imap_folder_selection_mode = "default"
account.imap_selected_folders = None
account.include_all_attachments = False
return account
def test_sync_continues_after_fetch_timeout():
"""A TimeoutError on fetch_message must not kill the entire sync run."""
db = MagicMock()
db.query.return_value.filter.return_value.all.return_value = []
imap = MagicMock()
imap.uid.side_effect = lambda *args: ("OK", [b"1 2"]) if args[0] == "search" else ("OK", [None])
account = _make_account()
fetch_calls: list = []
def _fetch_side_effect(_imap, uid):
fetch_calls.append(uid)
raise TimeoutError("The read operation timed out")
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.list_mailboxes", return_value=["INBOX"]):
with patch("forwarder.services.sync_service.select_folder_readonly", return_value=True):
with patch("forwarder.services.sync_service.fetch_message", side_effect=_fetch_side_effect):
with patch("forwarder.services.sync_service.report_error_with_cooldown"):
sync_run = sync_account(db, 1, dry_run=True)
assert sync_run.status == SyncRunStatus.completed
assert sync_run.messages_failed == 2
assert len(fetch_calls) == 2