feat: sync UI controls, message retry, and worker schedule guard
Add manual sync buttons with batch limit, nginx timeouts for long syncs, message retry endpoint, and fix worker to skip disabled accounts and refresh schedules from the database every 2 minutes.
This commit is contained in:
1 parent
20966501a8
commit
87b1ad4b8a
7 files changed
+385
-21
No files matched your search
+3
-3
@@ -13,9 +13,9 @@ server {
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_read_timeout 15s;
|
||||
proxy_connect_timeout 5s;
|
||||
proxy_send_timeout 15s;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_send_timeout 300s;
|
||||
}
|
||||
|
||||
location / {
|
||||
|
||||
@@ -77,6 +77,22 @@ export interface ConnectionTestResult {
|
||||
bizdocs_error: string | null
|
||||
}
|
||||
|
||||
export interface SyncRunResult {
|
||||
id: number
|
||||
account_id: number
|
||||
status: string
|
||||
dry_run: boolean
|
||||
max_emails: number | null
|
||||
messages_scanned: number
|
||||
messages_matched: number
|
||||
messages_forwarded: number
|
||||
messages_skipped: number
|
||||
messages_failed: number
|
||||
error_message: string | null
|
||||
started_at: string
|
||||
finished_at: string | null
|
||||
}
|
||||
|
||||
export interface TestPayload {
|
||||
imap_host: string
|
||||
imap_port: number
|
||||
@@ -100,6 +116,15 @@ export const api = {
|
||||
update: (id: number, data: Partial<AccountCreate>) =>
|
||||
request<Account>(`/accounts/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||
delete: (id: number) => request<void>(`/accounts/${id}`, { method: 'DELETE' }),
|
||||
sync: (id: number, opts?: { dry_run?: boolean; max_emails?: number }) => {
|
||||
const q = new URLSearchParams()
|
||||
if (opts?.dry_run) q.set('dry_run', 'true')
|
||||
if (opts?.max_emails != null) q.set('max_emails', String(opts.max_emails))
|
||||
const qs = q.toString()
|
||||
return request<SyncRunResult>(`/accounts/${id}/sync${qs ? '?' + qs : ''}`, {
|
||||
method: 'POST',
|
||||
})
|
||||
},
|
||||
},
|
||||
messages: {
|
||||
list: (params?: { account_id?: number; status?: string; limit?: number; offset?: number }) => {
|
||||
|
||||
@@ -3,7 +3,14 @@ import { api, Account, AccountCreate, DEFAULT_DESTINATION_EMAIL } from '../lib/a
|
||||
import { useAsync } from '../hooks/useApi'
|
||||
import Spinner from '../components/Spinner'
|
||||
import StatusBadge from '../components/StatusBadge'
|
||||
import { Plus, Pencil, Trash2, Wifi, X, Check } from 'lucide-react'
|
||||
import { Plus, Pencil, Trash2, Wifi, X, Check, Play, FlaskConical, RefreshCw } from 'lucide-react'
|
||||
|
||||
const DEFAULT_TEST_BATCH = 5
|
||||
|
||||
function formatSyncResult(r: import('../lib/api').SyncRunResult): string {
|
||||
const mode = r.dry_run ? 'Dry-run' : 'Sync'
|
||||
return `${mode}: ${r.messages_forwarded} enviados, ${r.messages_failed} falhas, ${r.messages_matched} match (${r.messages_scanned} lidos)`
|
||||
}
|
||||
|
||||
const EMPTY_FORM: AccountCreate = {
|
||||
name: '',
|
||||
@@ -18,7 +25,7 @@ const EMPTY_FORM: AccountCreate = {
|
||||
smtp_password: '',
|
||||
destination_email: DEFAULT_DESTINATION_EMAIL,
|
||||
sync_interval_minutes: 15,
|
||||
active: true,
|
||||
active: false,
|
||||
}
|
||||
|
||||
function AccountModal({
|
||||
@@ -183,7 +190,10 @@ export default function Accounts() {
|
||||
account: null,
|
||||
})
|
||||
const [testResults, setTestResults] = useState<Record<number, { ok: boolean; msg: string }>>({})
|
||||
const [syncResults, setSyncResults] = useState<Record<number, { ok: boolean; msg: string }>>({})
|
||||
const [testingId, setTestingId] = useState<number | null>(null)
|
||||
const [syncingId, setSyncingId] = useState<number | null>(null)
|
||||
const [testBatchSize, setTestBatchSize] = useState(DEFAULT_TEST_BATCH)
|
||||
|
||||
const openNew = () => setModal({ open: true, account: null })
|
||||
const openEdit = (a: Account) => setModal({ open: true, account: a })
|
||||
@@ -227,6 +237,45 @@ export default function Accounts() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleSync = async (
|
||||
id: number,
|
||||
opts: { dry_run?: boolean; max_emails?: number },
|
||||
confirmFull = false,
|
||||
) => {
|
||||
if (confirmFull) {
|
||||
const ok = confirm(
|
||||
'Sync completo processa todo o histórico IMAP com anexos PDF/XML/ZIP. Continuar?',
|
||||
)
|
||||
if (!ok) return
|
||||
}
|
||||
setSyncingId(id)
|
||||
setSyncResults((prev) => {
|
||||
const next = { ...prev }
|
||||
delete next[id]
|
||||
return next
|
||||
})
|
||||
try {
|
||||
const r = await api.accounts.sync(id, opts)
|
||||
const failed = r.status === 'failed'
|
||||
setSyncResults((prev) => ({
|
||||
...prev,
|
||||
[id]: {
|
||||
ok: !failed && r.messages_failed === 0,
|
||||
msg: failed && r.error_message
|
||||
? `Erro: ${r.error_message}`
|
||||
: formatSyncResult(r),
|
||||
},
|
||||
}))
|
||||
} catch (e) {
|
||||
setSyncResults((prev) => ({
|
||||
...prev,
|
||||
[id]: { ok: false, msg: e instanceof Error ? e.message : 'Erro no sync' },
|
||||
}))
|
||||
} finally {
|
||||
setSyncingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
@@ -253,6 +302,26 @@ export default function Accounts() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{accounts && accounts.length > 0 && (
|
||||
<div className="mb-4 flex flex-wrap items-center gap-3 text-sm text-gray-600 bg-blue-50 border border-blue-100 rounded-md px-4 py-3">
|
||||
<span>
|
||||
O worker automático só corre com <strong>Conta activa</strong>. Os botões ▶/🧪/↻
|
||||
abaixo são sync <strong>manual</strong> (funcionam mesmo com conta inactiva).
|
||||
</span>
|
||||
<label className="flex items-center gap-1.5 ml-auto">
|
||||
Limite teste:
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={50}
|
||||
value={testBatchSize}
|
||||
onChange={(e) => setTestBatchSize(Math.max(1, Number(e.target.value) || 1))}
|
||||
className="w-14 border border-gray-300 rounded px-2 py-0.5 text-sm"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{accounts && accounts.length === 0 && (
|
||||
<div className="text-center py-12 text-gray-400 text-sm">
|
||||
Nenhuma conta configurada. Clique em "Nova conta" para começar.
|
||||
@@ -280,19 +349,58 @@ export default function Accounts() {
|
||||
{a.destination_email}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<StatusBadge status={a.active ? 'active' : 'inactive'} />
|
||||
{testResults[a.id] && (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<StatusBadge status={a.active ? 'active' : 'inactive'} />
|
||||
{testResults[a.id] && (
|
||||
<span
|
||||
className={`text-xs ${testResults[a.id].ok ? 'text-green-600' : 'text-red-600'}`}
|
||||
>
|
||||
{testResults[a.id].msg}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{syncResults[a.id] && (
|
||||
<span
|
||||
className={`text-xs ${testResults[a.id].ok ? 'text-green-600' : 'text-red-600'}`}
|
||||
className={`text-xs ${syncResults[a.id].ok ? 'text-green-700' : 'text-red-600'}`}
|
||||
>
|
||||
{testResults[a.id].msg}
|
||||
{syncResults[a.id].msg}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<div className="flex items-center justify-end gap-1 flex-wrap">
|
||||
<button
|
||||
title={`Sync teste (${testBatchSize})`}
|
||||
onClick={() => handleSync(a.id, { max_emails: testBatchSize })}
|
||||
disabled={syncingId === a.id}
|
||||
className="p-1.5 text-gray-400 hover:text-green-600 disabled:opacity-40"
|
||||
>
|
||||
{syncingId === a.id ? (
|
||||
<Spinner className="h-4 w-4" />
|
||||
) : (
|
||||
<Play size={14} />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
title={`Dry-run (${testBatchSize})`}
|
||||
onClick={() =>
|
||||
handleSync(a.id, { dry_run: true, max_emails: testBatchSize })
|
||||
}
|
||||
disabled={syncingId === a.id}
|
||||
className="p-1.5 text-gray-400 hover:text-amber-600 disabled:opacity-40"
|
||||
>
|
||||
<FlaskConical size={14} />
|
||||
</button>
|
||||
<button
|
||||
title="Sync completo"
|
||||
onClick={() => handleSync(a.id, {}, true)}
|
||||
disabled={syncingId === a.id}
|
||||
className="p-1.5 text-gray-400 hover:text-indigo-600 disabled:opacity-40"
|
||||
>
|
||||
<RefreshCw size={14} />
|
||||
</button>
|
||||
<button
|
||||
title="Testar ligação"
|
||||
onClick={() => handleTest(a.id)}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
|
||||
from forwarder.api.deps import CurrentUser, DbSession
|
||||
from forwarder.api.schemas import MessageResponse
|
||||
from forwarder.db.models import Account, ForwardAttempt, Message, MessageStatus
|
||||
from forwarder.db.models import Account, Message, MessageStatus
|
||||
from forwarder.services.sync_service import retry_single_message
|
||||
|
||||
router = APIRouter(prefix="/messages", tags=["messages"])
|
||||
|
||||
@@ -65,3 +66,29 @@ def list_messages(
|
||||
|
||||
rows = query.offset(offset).limit(limit).all()
|
||||
return [_build_message_response(m, name) for m, name in rows]
|
||||
|
||||
|
||||
@router.post("/{message_id}/retry", response_model=MessageResponse)
|
||||
def retry_message(
|
||||
message_id: int,
|
||||
db: DbSession,
|
||||
_user: CurrentUser,
|
||||
) -> MessageResponse:
|
||||
message = db.get(Message, message_id)
|
||||
if message is None:
|
||||
raise HTTPException(status_code=404, detail="Message not found")
|
||||
if message.status == MessageStatus.forwarded:
|
||||
raise HTTPException(status_code=409, detail="Message already forwarded")
|
||||
|
||||
account = db.get(Account, message.account_id)
|
||||
if account is None:
|
||||
raise HTTPException(status_code=404, detail="Account not found")
|
||||
|
||||
try:
|
||||
updated = retry_single_message(db, message_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
return _build_message_response(updated, account.name)
|
||||
@@ -349,3 +349,86 @@ def sync_account(
|
||||
db.refresh(sync_run)
|
||||
|
||||
return sync_run
|
||||
|
||||
|
||||
def retry_single_message(db: Session, message_id: int) -> Message:
|
||||
message = db.get(Message, message_id)
|
||||
if message is None:
|
||||
raise ValueError(f"Message {message_id} not found")
|
||||
if message.status == MessageStatus.forwarded:
|
||||
raise ValueError("Message already forwarded")
|
||||
|
||||
account = get_account(db, message.account_id)
|
||||
imap_config = ImapConfig(
|
||||
host=account.imap_host,
|
||||
port=account.imap_port,
|
||||
user=account.imap_user,
|
||||
password=decrypt_password(account.imap_password_encrypted),
|
||||
)
|
||||
smtp_config = SmtpConfig(
|
||||
host=account.smtp_host,
|
||||
port=account.smtp_port,
|
||||
user=account.smtp_user,
|
||||
password=decrypt_password(account.smtp_password_encrypted),
|
||||
use_tls=account.smtp_use_tls,
|
||||
)
|
||||
|
||||
imap = None
|
||||
smtp = None
|
||||
try:
|
||||
imap = connect_imap(imap_config)
|
||||
if not select_folder_readonly(imap, message.folder):
|
||||
raise ValueError(f"Could not open folder: {message.folder}")
|
||||
|
||||
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}")
|
||||
|
||||
smtp = create_smtp_client(smtp_config)
|
||||
forward_email_as_eml(
|
||||
msg,
|
||||
smtp_config=smtp_config,
|
||||
destination_email=account.destination_email,
|
||||
smtp=smtp,
|
||||
)
|
||||
|
||||
message.status = MessageStatus.forwarded
|
||||
message.error_message = None
|
||||
message.updated_at = datetime.now(timezone.utc)
|
||||
_record_forward_attempt(db, message=message, success=True, dry_run=False)
|
||||
db.commit()
|
||||
db.refresh(message)
|
||||
logger.info("Retry forwarded: %s", message.subject)
|
||||
return message
|
||||
except Exception as exc:
|
||||
error_text = str(exc)
|
||||
message.status = MessageStatus.failed
|
||||
message.error_message = error_text
|
||||
message.updated_at = datetime.now(timezone.utc)
|
||||
_record_forward_attempt(
|
||||
db,
|
||||
message=message,
|
||||
success=False,
|
||||
dry_run=False,
|
||||
error_message=error_text,
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(message)
|
||||
report_error(
|
||||
exc,
|
||||
context_data={"message_id": message_id, "account_id": message.account_id},
|
||||
endpoint="messages:retry",
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
if imap is not None:
|
||||
try:
|
||||
imap.logout()
|
||||
except imaplib.IMAP4.error:
|
||||
pass
|
||||
if smtp is not None:
|
||||
try:
|
||||
smtp.quit()
|
||||
except smtplib.SMTPException:
|
||||
pass
|
||||
@@ -12,10 +12,28 @@ from forwarder.services.sync_service import sync_account
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SCHEDULE_REFRESH_MINUTES = 2
|
||||
|
||||
|
||||
def _account_job_id(account_id: int) -> str:
|
||||
return f"sync-account-{account_id}"
|
||||
|
||||
|
||||
def _sync_job(account_id: int) -> None:
|
||||
db = get_session_factory()()
|
||||
try:
|
||||
account = db.get(Account, account_id)
|
||||
if account is None:
|
||||
logger.warning("Scheduled sync skipped: account %s not found", account_id)
|
||||
return
|
||||
if not account.enabled:
|
||||
logger.info(
|
||||
"Scheduled sync skipped: account %s (%s) is disabled",
|
||||
account_id,
|
||||
account.name,
|
||||
)
|
||||
return
|
||||
|
||||
logger.info("Scheduled sync starting for account %s", account_id)
|
||||
sync_account(db, account_id, dry_run=False)
|
||||
except Exception as exc:
|
||||
@@ -32,24 +50,25 @@ def _sync_job(account_id: int) -> None:
|
||||
db.close()
|
||||
|
||||
|
||||
def run_worker(*, default_interval: int = 15) -> None:
|
||||
scheduler = BlockingScheduler()
|
||||
|
||||
def _refresh_account_schedules(scheduler: BlockingScheduler, *, default_interval: int) -> None:
|
||||
"""Reconcile APScheduler jobs with enabled accounts in the database."""
|
||||
db = get_session_factory()()
|
||||
enabled_ids: set[int] = set()
|
||||
try:
|
||||
accounts = db.query(Account).filter(Account.enabled.is_(True)).all()
|
||||
for account in accounts:
|
||||
enabled_ids.add(account.id)
|
||||
interval = account.sync_interval_minutes or default_interval
|
||||
scheduler.add_job(
|
||||
_sync_job,
|
||||
trigger=IntervalTrigger(minutes=interval),
|
||||
args=[account.id],
|
||||
id=f"sync-account-{account.id}",
|
||||
id=_account_job_id(account.id),
|
||||
replace_existing=True,
|
||||
max_instances=1,
|
||||
)
|
||||
logger.info(
|
||||
"Scheduled account %s (%s) every %s minutes",
|
||||
logger.debug(
|
||||
"Schedule ensured for account %s (%s) every %s minutes",
|
||||
account.id,
|
||||
account.name,
|
||||
interval,
|
||||
@@ -57,7 +76,35 @@ def run_worker(*, default_interval: int = 15) -> None:
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
if not scheduler.get_jobs():
|
||||
logger.warning("No enabled accounts — worker idle (restarts pick up new accounts)")
|
||||
for job in scheduler.get_jobs():
|
||||
if not job.id.startswith("sync-account-"):
|
||||
continue
|
||||
account_id = int(job.id.removeprefix("sync-account-"))
|
||||
if account_id not in enabled_ids:
|
||||
job.remove()
|
||||
logger.info("Removed schedule for disabled/deleted account %s", account_id)
|
||||
|
||||
|
||||
def run_worker(*, default_interval: int = 15) -> None:
|
||||
scheduler = BlockingScheduler()
|
||||
|
||||
_refresh_account_schedules(scheduler, default_interval=default_interval)
|
||||
|
||||
scheduler.add_job(
|
||||
_refresh_account_schedules,
|
||||
trigger=IntervalTrigger(minutes=SCHEDULE_REFRESH_MINUTES),
|
||||
args=[scheduler],
|
||||
kwargs={"default_interval": default_interval},
|
||||
id="refresh-account-schedules",
|
||||
replace_existing=True,
|
||||
max_instances=1,
|
||||
)
|
||||
|
||||
sync_jobs = [j for j in scheduler.get_jobs() if j.id.startswith("sync-account-")]
|
||||
if not sync_jobs:
|
||||
logger.warning(
|
||||
"No enabled accounts — worker idle (picks up changes every %s minutes)",
|
||||
SCHEDULE_REFRESH_MINUTES,
|
||||
)
|
||||
|
||||
scheduler.start()
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Tests for worker scheduler — disabled accounts must not sync automatically."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from apscheduler.schedulers.blocking import BlockingScheduler
|
||||
|
||||
from forwarder.worker import scheduler as sched
|
||||
|
||||
|
||||
class TestSyncJobGuard:
|
||||
def test_skips_when_account_disabled(self):
|
||||
db = MagicMock()
|
||||
account = MagicMock()
|
||||
account.enabled = False
|
||||
account.name = "Test Co"
|
||||
db.get.return_value = account
|
||||
|
||||
with patch.object(sched, "get_session_factory") as factory:
|
||||
factory.return_value = MagicMock(return_value=db)
|
||||
with patch.object(sched, "sync_account") as sync_account:
|
||||
sched._sync_job(42)
|
||||
|
||||
sync_account.assert_not_called()
|
||||
|
||||
def test_skips_when_account_missing(self):
|
||||
db = MagicMock()
|
||||
db.get.return_value = None
|
||||
|
||||
with patch.object(sched, "get_session_factory") as factory:
|
||||
factory.return_value = MagicMock(return_value=db)
|
||||
with patch.object(sched, "sync_account") as sync_account:
|
||||
sched._sync_job(99)
|
||||
|
||||
sync_account.assert_not_called()
|
||||
|
||||
def test_runs_when_account_enabled(self):
|
||||
db = MagicMock()
|
||||
account = MagicMock()
|
||||
account.enabled = True
|
||||
account.name = "Active Co"
|
||||
db.get.return_value = account
|
||||
|
||||
with patch.object(sched, "get_session_factory") as factory:
|
||||
factory.return_value = MagicMock(return_value=db)
|
||||
with patch.object(sched, "sync_account") as sync_account:
|
||||
sched._sync_job(1)
|
||||
|
||||
sync_account.assert_called_once_with(db, 1, dry_run=False)
|
||||
|
||||
|
||||
class TestRefreshSchedules:
|
||||
def test_removes_job_for_disabled_account(self):
|
||||
scheduler = BlockingScheduler()
|
||||
scheduler.add_job(lambda: None, "interval", seconds=3600, id="sync-account-7")
|
||||
|
||||
account = MagicMock()
|
||||
account.id = 1
|
||||
account.enabled = True
|
||||
account.name = "Active"
|
||||
account.sync_interval_minutes = 15
|
||||
|
||||
db = MagicMock()
|
||||
db.query.return_value.filter.return_value.all.return_value = [account]
|
||||
|
||||
with patch.object(sched, "get_session_factory") as factory:
|
||||
factory.return_value = MagicMock(return_value=db)
|
||||
sched._refresh_account_schedules(scheduler, default_interval=15)
|
||||
|
||||
job_ids = {j.id for j in scheduler.get_jobs()}
|
||||
assert "sync-account-1" in job_ids
|
||||
assert "sync-account-7" not in job_ids
|
||||
Reference in new issue
Block a user