feat: cap SMTP forwards at 200 per rolling hour

Count successful forward_attempts in the last hour and stop sync/retry
when MAX_FORWARDS_PER_HOUR is reached to protect domain sending limits.
This commit is contained in:
1sonhador committed 2026-07-01 10:09:52 +01:00
1 parent 95edd74d9f
commit 66d7189aa5
8 files changed
+110 -6

No files matched your search

+2
View File
@@ -15,6 +15,8 @@ ADMIN_PASSWORD=change_me
# Worker
SYNC_INTERVAL_MINUTES=15
# Max successful SMTP forwards per rolling hour (0 = unlimited)
MAX_FORWARDS_PER_HOUR=200
# Gitea webhook autodeploy (deploy-hook service on :9090)
DEPLOY_WEBHOOK_SECRET=change_me_random_64_chars
+1
View File
@@ -62,6 +62,7 @@ export interface RetryBatchResult {
attempted: number
succeeded: number
failed: number
rate_limited: boolean
errors: string[]
}
+9 -5
View File
@@ -58,10 +58,12 @@ export default function Emails() {
setActionMsg(null)
try {
const r = await api.messages.retryBatch({ limit })
const ok = r.succeeded > 0 && r.failed === 0
const ok = r.succeeded > 0 && r.failed === 0 && !r.rate_limited
setActionMsg({
ok,
text: `Batch: ${r.succeeded}/${r.attempted} OK${r.errors.length ? ` — ${r.errors[0]}` : ''}`,
text: r.rate_limited
? `Limite horário (200/h): ${r.succeeded}/${r.attempted} enviados neste lote.`
: `Batch: ${r.succeeded}/${r.attempted} OK${r.errors.length ? ` — ${r.errors[0]}` : ''}`,
})
reload()
} catch (e) {
@@ -89,7 +91,7 @@ export default function Emails() {
return
}
const ok = confirm(
`Repetir todas as ${failedCount} mensagens falhadas?\n\nIsto pode demorar vários minutos. Mantém a conta inactiva durante o processo.`,
`Repetir todas as ${failedCount} mensagens falhadas?\n\nEnvio limitado a 200/hora — continua automaticamente nas horas seguintes. Mantém a conta inactiva durante o processo.`,
)
if (!ok) return
@@ -108,11 +110,13 @@ export default function Emails() {
ok: false,
text: `A repetir… ${totalSucceeded} OK, ${totalFailed} falhas (${totalAttempted} processadas)`,
})
if (r.attempted === 0) break
if (r.attempted === 0 || r.rate_limited) break
}
setActionMsg({
ok: totalFailed === 0,
text: `Concluído: ${totalSucceeded} reencaminhadas, ${totalFailed} falharam (${totalAttempted} processadas).`,
text: `Concluído: ${totalSucceeded} reencaminhadas, ${totalFailed} falharam (${totalAttempted} processadas).${
totalAttempted < failedCount ? ' Limite horário — continua mais tarde.' : ''
}`,
})
reload()
} catch (e) {
+10 -1
View File
@@ -7,6 +7,7 @@ from forwarder.api.deps import CurrentUser, DbSession
from forwarder.api.schemas import MessageListResponse, MessageResponse
from forwarder.db.models import Account, Message, MessageStatus
from forwarder.services.sync_service import retry_single_message
from forwarder.services.rate_limit import ForwardRateLimitError
router = APIRouter(prefix="/messages", tags=["messages"])
@@ -95,6 +96,7 @@ def retry_batch(
succeeded = 0
failed = 0
attempted = 0
rate_limited = False
errors: list[str] = []
while True:
@@ -115,18 +117,23 @@ def retry_batch(
try:
retry_single_message(db, message.id)
succeeded += 1
except ForwardRateLimitError as exc:
rate_limited = True
errors.append(str(exc))
break
except Exception as exc:
failed += 1
errors.append(f"#{message.id}: {exc}")
attempted += 1
if not all_failed:
if rate_limited or not all_failed:
break
return {
"attempted": attempted,
"succeeded": succeeded,
"failed": failed,
"rate_limited": rate_limited,
"errors": errors[:10],
}
@@ -149,6 +156,8 @@ def retry_message(
try:
updated = retry_single_message(db, message_id)
except ForwardRateLimitError as exc:
raise HTTPException(status_code=429, detail=str(exc)) from exc
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc:
+1
View File
@@ -18,6 +18,7 @@ class Settings(BaseSettings):
admin_username: str = "admin"
admin_password: str = "change-me"
sync_interval_minutes: int = 15
max_forwards_per_hour: int = 200
api_host: str = "0.0.0.0"
api_port: int = 8000
+44
View File
@@ -0,0 +1,44 @@
"""Outbound SMTP forward rate limiting (protects domain sending reputation)."""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from sqlalchemy import func
from sqlalchemy.orm import Session
from forwarder.config import get_settings
from forwarder.db.models import ForwardAttempt
class ForwardRateLimitError(Exception):
"""Raised when the hourly forward cap is reached."""
def __init__(self, *, limit: int, used: int) -> None:
self.limit = limit
self.used = used
super().__init__(f"Forward rate limit reached ({used}/{limit} per hour)")
def count_forwards_last_hour(db: Session) -> int:
since = datetime.now(timezone.utc) - timedelta(hours=1)
return (
db.query(func.count(ForwardAttempt.id))
.filter(
ForwardAttempt.success.is_(True),
ForwardAttempt.dry_run.is_(False),
ForwardAttempt.created_at >= since,
)
.scalar()
or 0
)
def check_forward_allowed(db: Session) -> None:
settings = get_settings()
limit = settings.max_forwards_per_hour
if limit <= 0:
return
used = count_forwards_last_hour(db)
if used >= limit:
raise ForwardRateLimitError(limit=limit, used=used)
+7
View File
@@ -32,6 +32,7 @@ from forwarder.email.parsing import (
from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_invoice_attachments
from forwarder.error_reporter import report_error, report_error_with_cooldown
from forwarder.services.account_service import get_account
from forwarder.services.rate_limit import ForwardRateLimitError, check_forward_allowed
logger = logging.getLogger(__name__)
@@ -256,6 +257,7 @@ def sync_account(
continue
try:
check_forward_allowed(db)
forward_invoice_attachments(
msg,
smtp_config=smtp_config,
@@ -282,6 +284,10 @@ def sync_account(
result.messages_forwarded += 1
handled_count += 1
logger.info("Forwarded: %s", subject)
except ForwardRateLimitError as exc:
logger.warning("Hourly forward limit reached, stopping sync: %s", exc)
stop_all = True
break
except Exception as exc:
error_text = str(exc)
logger.error("Forward failed for %s: %s", subject, error_text)
@@ -389,6 +395,7 @@ def retry_single_message(db: Session, message_id: int) -> Message:
smtp = create_smtp_client(smtp_config)
allowed_extensions = set(account.allowed_extensions or [])
check_forward_allowed(db)
forward_invoice_attachments(
msg,
smtp_config=smtp_config,
+36
View File
@@ -0,0 +1,36 @@
"""Rate limit tests."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import pytest
from forwarder.services.rate_limit import ForwardRateLimitError, check_forward_allowed
def test_check_forward_allowed_when_under_limit():
db = MagicMock()
with patch("forwarder.services.rate_limit.get_settings") as settings:
settings.return_value.max_forwards_per_hour = 200
with patch("forwarder.services.rate_limit.count_forwards_last_hour", return_value=199):
check_forward_allowed(db)
def test_check_forward_allowed_raises_at_limit():
db = MagicMock()
with patch("forwarder.services.rate_limit.get_settings") as settings:
settings.return_value.max_forwards_per_hour = 200
with patch("forwarder.services.rate_limit.count_forwards_last_hour", return_value=200):
with pytest.raises(ForwardRateLimitError) as exc:
check_forward_allowed(db)
assert exc.value.limit == 200
assert exc.value.used == 200
def test_unlimited_when_config_zero():
db = MagicMock()
with patch("forwarder.services.rate_limit.get_settings") as settings:
settings.return_value.max_forwards_per_hour = 0
with patch("forwarder.services.rate_limit.count_forwards_last_hour", return_value=9999):
check_forward_allowed(db)