fix: route retry-batch through forward queue instead of bulk SMTP

all=true only confirms failed messages are queued; each tick respects 5/min and 200/h limits.
This commit is contained in:
1sonhador committed 2026-07-01 10:19:39 +01:00
1 parent 9b966cf325
commit 2ee2306c3e
3 files changed
+54 -71

No files matched your search

+3 -1
View File
@@ -68,12 +68,14 @@ export interface ForwardQueueStatus {
eta_hours_at_limit: number | null
}
export interface RetryBatchResult {
export interface RetryBatchResult extends Partial<ForwardQueueStatus> {
queued?: boolean
attempted: number
succeeded: number
failed: number
rate_limited: boolean
errors: string[]
pending_total?: number
}
export interface MessageList {
+26 -30
View File
@@ -64,18 +64,21 @@ export default function Emails() {
}
}
const handleRetryBatch = async (limit: number) => {
const handleRetryBatch = async () => {
setBatchRetrying(true)
setActionMsg(null)
try {
const r = await api.messages.retryBatch({ limit })
const ok = r.succeeded > 0 && r.failed === 0 && !r.rate_limited
const r = await api.messages.retryBatch({ limit: 5 })
const ok = !r.rate_limited && (r.succeeded > 0 || r.pending_total === 0)
setActionMsg({
ok,
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]}` : ''}`,
? `Fila pausada — limite horário (${r.max_forwards_per_hour ?? 200}/h). ${r.pending_total ?? r.pending ?? '?'} ainda pendentes.`
: r.attempted === 0
? 'Fila vazia — nada a reenviar.'
: `Fila: ${r.succeeded}/${r.attempted} enviados neste tick (${r.pending_total ?? '?'} pendentes).`,
})
await loadQueueStatus()
reload()
} catch (e) {
setActionMsg({
@@ -137,40 +140,33 @@ export default function Emails() {
setActionMsg({ ok: true, text: 'Não há mensagens falhadas para repetir.' })
return
}
const batch = queueInfo?.batch_size_per_tick ?? 5
const maxHour = queueInfo?.max_forwards_per_hour ?? 200
const ok = confirm(
`Repetir todas as ${failedCount} mensagens falhadas?\n\n` +
`Preferir "Reenviar todas (fila)" — envia ${queueInfo?.batch_size_per_tick ?? 5}/min, máx. ${queueInfo?.max_forwards_per_hour ?? 200}/hora.`,
`Enfileirar ${failedCount} mensagens falhadas para reenvio gradual?\n\n` +
`O worker envia no máximo ${batch}/min (máx. ${maxHour}/hora). Não há envio em massa.`,
)
if (!ok) return
setBatchRetrying(true)
setActionMsg({ ok: false, text: `A repetir ${failedCount} mensagens…` })
let totalSucceeded = 0
let totalFailed = 0
let totalAttempted = 0
setActionMsg(null)
try {
while (true) {
const r = await api.messages.retryBatch({ limit: 50 })
totalSucceeded += r.succeeded
totalFailed += r.failed
totalAttempted += r.attempted
setActionMsg({
ok: false,
text: `A repetir… ${totalSucceeded} OK, ${totalFailed} falhas (${totalAttempted} processadas)`,
})
if (r.attempted === 0 || r.rate_limited) break
}
const r = await api.messages.retryBatch({ all: true })
const pending = r.pending ?? failedCount
const eta = r.eta_hours_at_limit
setActionMsg({
ok: totalFailed === 0,
text: `Concluído: ${totalSucceeded} reencaminhadas, ${totalFailed} falharam (${totalAttempted} processadas).${
totalAttempted < failedCount ? ' Limite horário — continua mais tarde.' : ''
}`,
ok: true,
text:
pending === 0
? 'Não há mensagens falhadas na fila.'
: `${pending} mensagens na fila. ETA ~${eta ?? '?'}h. O worker processa automaticamente.`,
})
await loadQueueStatus()
reload()
} catch (e) {
setActionMsg({
ok: false,
text: e instanceof Error ? e.message : 'Retry de todas falhou',
text: e instanceof Error ? e.message : 'Falha ao enfileirar',
})
} finally {
setBatchRetrying(false)
@@ -197,11 +193,11 @@ export default function Emails() {
<>
<button
type="button"
onClick={() => handleRetryBatch(5)}
onClick={handleRetryBatch}
disabled={batchRetrying || loading}
className="text-sm px-3 py-1.5 border border-amber-300 text-amber-800 bg-amber-50 rounded-md hover:bg-amber-100 disabled:opacity-40"
>
{batchRetrying ? 'A repetir…' : 'Repetir 5 falhadas'}
{batchRetrying ? 'A processar…' : 'Processar tick da fila (5)'}
</button>
<button
type="button"
@@ -209,7 +205,7 @@ export default function Emails() {
disabled={batchRetrying || loading}
className="text-sm px-3 py-1.5 border border-indigo-300 text-indigo-800 bg-indigo-50 rounded-md hover:bg-indigo-100 disabled:opacity-40"
>
Repetir todas as falhadas
Enfileirar todas as falhadas
</button>
</>
)}
+25 -40
View File
@@ -115,50 +115,35 @@ def retry_batch(
account_id: int | None = Query(default=None),
all_failed: bool = Query(default=False, alias="all"),
) -> dict:
"""Retry failed messages. Use all=true to process every failed message in batches."""
batch_size = 100 if all_failed else limit
succeeded = 0
failed = 0
attempted = 0
rate_limited = False
errors: list[str] = []
"""Retry failed messages via the forward queue (never bulk SMTP).
while True:
query = db.query(Message).filter(Message.status == MessageStatus.failed)
Use all=true to confirm all failed messages are queued for the worker.
Otherwise runs one queue tick (max batch_size per minute, hourly cap).
"""
_ = limit # kept for API compat; queue batch size comes from settings
if all_failed:
status = get_queue_status(db)
pending_query = db.query(Message).filter(Message.status == MessageStatus.failed)
if account_id is not None:
query = query.filter(Message.account_id == account_id)
messages = query.order_by(Message.id.asc()).limit(batch_size).all()
if not messages:
break
for message in messages:
account = db.get(Account, message.account_id)
if account is None:
failed += 1
attempted += 1
errors.append(f"#{message.id}: account missing")
continue
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 rate_limited or not all_failed:
break
pending_query = pending_query.filter(Message.account_id == account_id)
pending = pending_query.count()
return {
"queued": True,
"attempted": 0,
"succeeded": 0,
"failed": 0,
"rate_limited": status["forwards_remaining_this_hour"] == 0,
"errors": [],
"pending": pending,
**status,
}
result = process_forward_queue(db)
return {
"attempted": attempted,
"succeeded": succeeded,
"failed": failed,
"rate_limited": rate_limited,
"errors": errors[:10],
"queued": False,
"errors": [],
**result.as_dict(),
}