Merge branch 'main' into task/BIT-26141-fix-test-endpoint
This commit is contained in:
commit
b1382b4b95
27 files changed
+1719
-145
No files matched your search
@@ -15,6 +15,11 @@ ADMIN_PASSWORD=change_me
|
||||
|
||||
# Worker
|
||||
SYNC_INTERVAL_MINUTES=15
|
||||
# Max successful SMTP forwards per rolling hour (0 = unlimited)
|
||||
MAX_FORWARDS_PER_HOUR=200
|
||||
# Forward queue: process at most N failed messages per tick
|
||||
FORWARD_QUEUE_BATCH_SIZE=5
|
||||
FORWARD_QUEUE_INTERVAL_SECONDS=60
|
||||
|
||||
# Gitea webhook autodeploy (deploy-hook service on :9090)
|
||||
DEPLOY_WEBHOOK_SECRET=change_me_random_64_chars
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# BizDocs Forwarder
|
||||
|
||||
Multi-account IMAP → BizDocs forwarder: detect invoice attachments (PDF/XML/ZIP), re-send via SMTP as `.eml`.
|
||||
Multi-account IMAP → BizDocs forwarder: detect invoice attachments (PDF/XML/ZIP), forward original email via SMTP.
|
||||
|
||||
- **Repo:** https://git.bitreport.pt/BitReport.pt/forwarder
|
||||
- **Paperclip:** http://10.10.50.17:3100/BIT/projects/bizdocs-forwarder
|
||||
|
||||
+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 / {
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
+77
-5
@@ -50,14 +50,45 @@ export interface Message {
|
||||
account_id: number
|
||||
account_name: string
|
||||
message_uid: string
|
||||
message_key: string
|
||||
subject: string
|
||||
sender: string
|
||||
received_at: string
|
||||
status: 'pending' | 'forwarded' | 'failed'
|
||||
date: string
|
||||
folder: string
|
||||
created_at: string
|
||||
status: 'pending' | 'forwarded' | 'failed' | 'missing_from_mailbox'
|
||||
error: string | null
|
||||
forwarded_at: string | null
|
||||
}
|
||||
|
||||
export interface ForwardQueueStatus {
|
||||
pending: number
|
||||
forwards_used_last_hour: number
|
||||
forwards_remaining_this_hour: number | null
|
||||
max_forwards_per_hour: number
|
||||
batch_size_per_tick: number
|
||||
tick_interval_seconds: number
|
||||
eta_hours_at_limit: number | null
|
||||
}
|
||||
|
||||
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 {
|
||||
items: Message[]
|
||||
total: number
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
||||
export interface Stats {
|
||||
accounts_total: number
|
||||
accounts_active: number
|
||||
@@ -65,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
|
||||
}
|
||||
|
||||
@@ -77,6 +109,23 @@ 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
|
||||
messages_missing_from_mailbox?: number
|
||||
error_message: string | null
|
||||
started_at: string
|
||||
finished_at: string | null
|
||||
}
|
||||
|
||||
export interface TestPayload {
|
||||
imap_host: string
|
||||
imap_port: number
|
||||
@@ -100,17 +149,40 @@ 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 }) => {
|
||||
const q = new URLSearchParams()
|
||||
if (params?.account_id) q.set('account_id', String(params.account_id))
|
||||
if (params?.status) q.set('status', params.status)
|
||||
if (params?.limit) q.set('limit', String(params.limit))
|
||||
if (params?.offset) q.set('offset', String(params.offset))
|
||||
return request<Message[]>(`/messages${q.toString() ? '?' + q : ''}`)
|
||||
if (params?.limit != null) q.set('limit', String(params.limit))
|
||||
if (params?.offset != null) q.set('offset', String(params.offset))
|
||||
return request<MessageList>(`/messages${q.toString() ? '?' + q : ''}`)
|
||||
},
|
||||
retry: (id: number) => request<void>(`/messages/${id}/retry`, { method: 'POST' }),
|
||||
retry: (id: number) => request<Message>(`/messages/${id}/retry`, { method: 'POST' }),
|
||||
retryBatch: (opts?: { limit?: number; account_id?: number; all?: boolean }) => {
|
||||
const q = new URLSearchParams()
|
||||
if (opts?.all) q.set('all', 'true')
|
||||
else if (opts?.limit != null) q.set('limit', String(opts.limit))
|
||||
if (opts?.account_id != null) q.set('account_id', String(opts.account_id))
|
||||
return request<RetryBatchResult>(`/messages/retry-batch${q.toString() ? '?' + q : ''}`, {
|
||||
method: 'POST',
|
||||
})
|
||||
},
|
||||
queueStatus: () => request<ForwardQueueStatus>('/messages/queue/status'),
|
||||
requeueForwarded: () =>
|
||||
request<{ requeued: number } & ForwardQueueStatus>('/messages/requeue-forwarded', {
|
||||
method: 'POST',
|
||||
}),
|
||||
},
|
||||
stats: {
|
||||
get: () => request<Stats>('/stats'),
|
||||
|
||||
@@ -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({
|
||||
@@ -124,7 +131,7 @@ function AccountModal({
|
||||
<fieldset className="border border-gray-200 rounded-md p-3">
|
||||
<legend className="text-xs font-semibold text-gray-500 px-1">BizDocs (destino)</legend>
|
||||
<p className="text-xs text-gray-500 mb-2">
|
||||
Email para onde as facturas são reencaminhadas via SMTP (.eml).
|
||||
Email para onde são enviados os anexos de fatura (PDF/XML/ZIP) — email limpo, sem reencaminhar o original.
|
||||
</p>
|
||||
{field(
|
||||
'Email destino',
|
||||
@@ -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)}
|
||||
|
||||
+315
-59
@@ -1,29 +1,186 @@
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { api, Message } from '../lib/api'
|
||||
import { useAsync } from '../hooks/useApi'
|
||||
import Spinner from '../components/Spinner'
|
||||
import StatusBadge from '../components/StatusBadge'
|
||||
import { RefreshCw, RotateCcw } from 'lucide-react'
|
||||
import { ChevronLeft, ChevronRight, RefreshCw, RotateCcw } from 'lucide-react'
|
||||
|
||||
const PAGE_SIZE = 25
|
||||
|
||||
function formatMessageKey(key: string): string {
|
||||
const at = key.indexOf('@')
|
||||
if (at > 0) {
|
||||
return key.slice(0, 8) + '…' + key.slice(at)
|
||||
}
|
||||
return key.length > 20 ? key.slice(0, 20) + '…' : key
|
||||
}
|
||||
|
||||
export default function Emails() {
|
||||
const [filterStatus, setFilterStatus] = useState('')
|
||||
const [page, setPage] = useState(0)
|
||||
const [retryingId, setRetryingId] = useState<number | null>(null)
|
||||
const [actionMsg, setActionMsg] = useState<{ ok: boolean; text: string } | null>(null)
|
||||
const [batchRetrying, setBatchRetrying] = useState(false)
|
||||
const [queueInfo, setQueueInfo] = useState<import('../lib/api').ForwardQueueStatus | null>(null)
|
||||
|
||||
const { data: messages, loading, error, reload } = useAsync<Message[]>(
|
||||
() => api.messages.list({ status: filterStatus || undefined, limit: 100 }),
|
||||
[filterStatus],
|
||||
const loadQueueStatus = async () => {
|
||||
try {
|
||||
setQueueInfo(await api.messages.queueStatus())
|
||||
} catch {
|
||||
setQueueInfo(null)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadQueueStatus()
|
||||
const t = setInterval(loadQueueStatus, 30_000)
|
||||
return () => clearInterval(t)
|
||||
}, [filterStatus, page])
|
||||
|
||||
const { data, loading, error, reload } = useAsync(
|
||||
() =>
|
||||
api.messages.list({
|
||||
status: filterStatus || undefined,
|
||||
limit: PAGE_SIZE,
|
||||
offset: page * PAGE_SIZE,
|
||||
}),
|
||||
[filterStatus, page],
|
||||
)
|
||||
|
||||
const messages = data?.items
|
||||
const total = data?.total ?? 0
|
||||
const pageStart = total === 0 ? 0 : page * PAGE_SIZE + 1
|
||||
const pageEnd = Math.min((page + 1) * PAGE_SIZE, total)
|
||||
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
|
||||
const canPrev = page > 0
|
||||
const canNext = (page + 1) * PAGE_SIZE < total
|
||||
|
||||
const handleRetry = async (id: number) => {
|
||||
setRetryingId(id)
|
||||
setActionMsg(null)
|
||||
try {
|
||||
await api.messages.retry(id)
|
||||
setActionMsg({ ok: true, text: `Mensagem #${id} reencaminhada com sucesso.` })
|
||||
reload()
|
||||
} catch (e) {
|
||||
setActionMsg({
|
||||
ok: false,
|
||||
text: e instanceof Error ? e.message : `Retry falhou (#${id})`,
|
||||
})
|
||||
} finally {
|
||||
setRetryingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRetryBatch = async () => {
|
||||
setBatchRetrying(true)
|
||||
setActionMsg(null)
|
||||
try {
|
||||
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
|
||||
? `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({
|
||||
ok: false,
|
||||
text: e instanceof Error ? e.message : 'Retry em lote falhou',
|
||||
})
|
||||
} finally {
|
||||
setBatchRetrying(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setPage(0)
|
||||
}, [filterStatus])
|
||||
|
||||
const handleRequeueAll = async () => {
|
||||
const forwarded = queueInfo
|
||||
? (await api.stats.get().catch(() => null))?.messages_forwarded
|
||||
: null
|
||||
const ok = confirm(
|
||||
`Colocar todas as mensagens reencaminhadas na fila para reenvio?\n\n` +
|
||||
`O worker envia no máximo ${queueInfo?.batch_size_per_tick ?? 5} por minuto ` +
|
||||
`(limite ${queueInfo?.max_forwards_per_hour ?? 200}/hora). ` +
|
||||
`BizDocs ignora duplicados.\n\n` +
|
||||
(forwarded != null ? `${forwarded} mensagens serão reenviadas gradualmente.` : ''),
|
||||
)
|
||||
if (!ok) return
|
||||
setBatchRetrying(true)
|
||||
setActionMsg(null)
|
||||
try {
|
||||
const r = await api.messages.requeueForwarded()
|
||||
setActionMsg({
|
||||
ok: true,
|
||||
text: `${r.requeued} mensagens na fila. ETA ~${r.eta_hours_at_limit ?? '?'}h (${r.pending} pendentes).`,
|
||||
})
|
||||
await loadQueueStatus()
|
||||
reload()
|
||||
} catch (e) {
|
||||
setActionMsg({
|
||||
ok: false,
|
||||
text: e instanceof Error ? e.message : 'Falha ao enfileirar',
|
||||
})
|
||||
} finally {
|
||||
setBatchRetrying(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRetryAll = async () => {
|
||||
let failedCount = filterStatus === 'failed' ? total : 0
|
||||
if (failedCount === 0) {
|
||||
try {
|
||||
const stats = await api.stats.get()
|
||||
failedCount = stats.messages_failed
|
||||
} catch {
|
||||
failedCount = 0
|
||||
}
|
||||
}
|
||||
if (failedCount === 0) {
|
||||
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(
|
||||
`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(null)
|
||||
try {
|
||||
const r = await api.messages.retryBatch({ all: true })
|
||||
const pending = r.pending ?? failedCount
|
||||
const eta = r.eta_hours_at_limit
|
||||
setActionMsg({
|
||||
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 : 'Falha ao enfileirar',
|
||||
})
|
||||
} finally {
|
||||
setBatchRetrying(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
@@ -32,6 +189,34 @@ export default function Emails() {
|
||||
<p className="text-sm text-gray-500 mt-0.5">Histórico de mensagens processadas</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleRequeueAll}
|
||||
disabled={batchRetrying || loading}
|
||||
className="text-sm px-3 py-1.5 border border-emerald-300 text-emerald-800 bg-emerald-50 rounded-md hover:bg-emerald-100 disabled:opacity-40"
|
||||
>
|
||||
{batchRetrying ? 'A enfileirar…' : 'Reenviar todas (fila)'}
|
||||
</button>
|
||||
{(filterStatus === 'failed' || filterStatus === '') && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
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 processar…' : 'Processar tick da fila (5)'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleRetryAll}
|
||||
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"
|
||||
>
|
||||
Enfileirar todas as falhadas
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<select
|
||||
value={filterStatus}
|
||||
onChange={(e) => setFilterStatus(e.target.value)}
|
||||
@@ -41,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}
|
||||
@@ -51,78 +237,148 @@ export default function Emails() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{queueInfo && (queueInfo.pending > 0 || queueInfo.forwards_used_last_hour > 0) && (
|
||||
<div className="mb-4 px-4 py-3 rounded-md text-sm border bg-sky-50 border-sky-200 text-sky-900">
|
||||
<strong>Fila de reenvio:</strong> {queueInfo.pending} pendente
|
||||
{queueInfo.pending > 0 && queueInfo.eta_hours_at_limit != null && (
|
||||
<> — ETA ~{queueInfo.eta_hours_at_limit}h</>
|
||||
)}
|
||||
{' · '}
|
||||
{queueInfo.forwards_used_last_hour}/{queueInfo.max_forwards_per_hour} enviados na última hora
|
||||
{queueInfo.forwards_remaining_this_hour != null && (
|
||||
<> ({queueInfo.forwards_remaining_this_hour} restantes)</>
|
||||
)}
|
||||
{' · '}
|
||||
{queueInfo.batch_size_per_tick} por minuto
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading && !messages && (
|
||||
<div className="flex justify-center py-12">
|
||||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
{actionMsg && (
|
||||
<div
|
||||
className={`mb-4 px-4 py-3 rounded-md text-sm border ${
|
||||
actionMsg.ok
|
||||
? 'bg-green-50 border-green-200 text-green-800'
|
||||
: 'bg-red-50 border-red-200 text-red-700'
|
||||
}`}
|
||||
>
|
||||
{actionMsg.text}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{messages && messages.length === 0 && (
|
||||
{messages && messages.length === 0 && !loading && (
|
||||
<div className="text-center py-12 text-gray-400 text-sm">
|
||||
Nenhuma mensagem{filterStatus ? ` com estado "${filterStatus}"` : ''}.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{messages && messages.length > 0 && (
|
||||
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-gray-50 border-b border-gray-200">
|
||||
<tr>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Conta</th>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Assunto</th>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Remetente</th>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Recebido</th>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Estado</th>
|
||||
<th className="text-right px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{messages.map((m) => (
|
||||
<tr key={m.id} className="hover:bg-gray-50">
|
||||
<td className="px-4 py-3 text-gray-500 text-xs">{m.account_name}</td>
|
||||
<td className="px-4 py-3 font-medium truncate max-w-xs" title={m.subject}>
|
||||
{m.subject || '(sem assunto)'}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-600 text-xs truncate max-w-[180px]">{m.sender}</td>
|
||||
<td className="px-4 py-3 text-gray-500 text-xs whitespace-nowrap">
|
||||
{new Date(m.received_at).toLocaleString('pt-PT')}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div>
|
||||
<StatusBadge status={m.status} />
|
||||
{m.error && (
|
||||
<p className="text-xs text-red-500 mt-0.5 truncate max-w-xs" title={m.error}>
|
||||
{m.error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right">
|
||||
{m.status === 'failed' && (
|
||||
<button
|
||||
title="Tentar novamente"
|
||||
onClick={() => handleRetry(m.id)}
|
||||
disabled={retryingId === m.id}
|
||||
className="p-1.5 text-gray-400 hover:text-indigo-600 disabled:opacity-40"
|
||||
>
|
||||
{retryingId === m.id ? (
|
||||
<Spinner className="h-4 w-4" />
|
||||
) : (
|
||||
<RotateCcw size={14} />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
<>
|
||||
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-gray-50 border-b border-gray-200">
|
||||
<tr>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Conta</th>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Assunto</th>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Remetente</th>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Data email</th>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Pasta</th>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Estado</th>
|
||||
<th className="text-right px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Ações</th>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{messages.map((m: Message) => (
|
||||
<tr key={m.id} className="hover:bg-gray-50">
|
||||
<td className="px-4 py-3 text-gray-500 text-xs">{m.account_name}</td>
|
||||
<td className="px-4 py-3 font-medium truncate max-w-xs">
|
||||
<span title={`${m.message_key}\nProcessado: ${new Date(m.created_at).toLocaleString('pt-PT')}`}>
|
||||
{m.subject || '(sem assunto)'}
|
||||
</span>
|
||||
<p className="text-xs text-gray-400 font-normal truncate" title={m.message_key}>
|
||||
{formatMessageKey(m.message_key)}
|
||||
</p>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-600 text-xs truncate max-w-[180px]">{m.sender}</td>
|
||||
<td className="px-4 py-3 text-gray-500 text-xs whitespace-nowrap">
|
||||
{new Date(m.received_at).toLocaleString('pt-PT')}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-500 text-xs truncate max-w-[120px]" title={m.folder}>
|
||||
{m.folder}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div>
|
||||
<StatusBadge status={m.status} />
|
||||
{m.error && (
|
||||
<p className="text-xs text-red-500 mt-0.5 truncate max-w-xs" title={m.error}>
|
||||
{m.error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right">
|
||||
{m.status === 'failed' && (
|
||||
<button
|
||||
title="Tentar novamente"
|
||||
onClick={() => handleRetry(m.id)}
|
||||
disabled={retryingId === m.id}
|
||||
className="p-1.5 text-gray-400 hover:text-indigo-600 disabled:opacity-40"
|
||||
>
|
||||
{retryingId === m.id ? (
|
||||
<Spinner className="h-4 w-4" />
|
||||
) : (
|
||||
<RotateCcw size={14} />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between mt-4 text-sm text-gray-600">
|
||||
<span>
|
||||
{total === 0
|
||||
? '0 mensagens'
|
||||
: `${pageStart}–${pageEnd} de ${total} mensagem${total === 1 ? '' : 's'}`}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-gray-400">
|
||||
Página {page + 1} de {totalPages}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPage((p) => p - 1)}
|
||||
disabled={!canPrev || loading}
|
||||
className="flex items-center gap-1 px-3 py-1.5 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
|
||||
>
|
||||
<ChevronLeft size={14} />
|
||||
Anterior
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
disabled={!canNext || loading}
|
||||
className="flex items-center gap-1 px-3 py-1.5 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
|
||||
>
|
||||
Seguinte
|
||||
<ChevronRight size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -49,17 +49,23 @@ mkdir -p "$(dirname "$LOG_FILE")"
|
||||
|
||||
log "Building API + worker ($GIT_SHA)"
|
||||
{
|
||||
$COMPOSE build --build-arg FORWARDER_GIT_SHA="$GIT_SHA" api worker
|
||||
$COMPOSE up -d --force-recreate api worker
|
||||
$COMPOSE build --build-arg FORWARDER_GIT_SHA="$GIT_SHA" api worker migrate
|
||||
log "Running migrations"
|
||||
$COMPOSE run --rm migrate
|
||||
$COMPOSE up -d --force-recreate api worker
|
||||
log "Building admin UI ($GIT_SHA)"
|
||||
$COMPOSE build --build-arg GIT_SHA="$GIT_SHA" web
|
||||
$COMPOSE up -d --force-recreate web
|
||||
curl -sf --max-time 10 http://127.0.0.1:8000/api/health >/dev/null
|
||||
for i in 1 2 3 4 5; do
|
||||
curl -sf --max-time 8 http://127.0.0.1:8000/api/health >/dev/null && break
|
||||
log "API not ready yet (attempt $i/5), retrying in 5s..."
|
||||
sleep 5
|
||||
done
|
||||
curl -sf --max-time 8 http://127.0.0.1:8000/api/health >/dev/null
|
||||
write_status "ok $GIT_SHA $(date -Iseconds)"
|
||||
log "Deploy OK ($GIT_SHA)"
|
||||
log "Refreshing deploy-hook (self-restart — runs detached)"
|
||||
$COMPOSE build deploy-hook
|
||||
nohup $COMPOSE up -d --force-recreate deploy-hook &
|
||||
} >> "$LOG_FILE" 2>&1
|
||||
# webhook: http://forwarder-hook.bitreport.pt/ (NPM proxy, commit 2026-07-01T01:13:13Z)
|
||||
@@ -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"
|
||||
)
|
||||
@@ -1,10 +1,22 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from sqlalchemy import func
|
||||
|
||||
from forwarder.api.deps import CurrentUser, DbSession
|
||||
from forwarder.api.schemas import MessageResponse
|
||||
from forwarder.db.models import Account, ForwardAttempt, Message, MessageStatus
|
||||
from forwarder.api.schemas import MessageListResponse, MessageResponse
|
||||
from forwarder.db.models import Account, Message, MessageStatus
|
||||
from forwarder.services.forward_queue_service import (
|
||||
get_queue_status,
|
||||
process_forward_queue,
|
||||
requeue_forwarded_messages,
|
||||
)
|
||||
from forwarder.email.parsing import parse_email_datetime
|
||||
from forwarder.services.sync_service import (
|
||||
MessageMissingFromMailboxError,
|
||||
retry_single_message,
|
||||
)
|
||||
from forwarder.services.rate_limit import ForwardRateLimitError
|
||||
|
||||
router = APIRouter(prefix="/messages", tags=["messages"])
|
||||
|
||||
@@ -16,6 +28,9 @@ def _build_message_response(m: Message, account_name: str) -> MessageResponse:
|
||||
if success_attempts:
|
||||
forwarded_at = max(a.created_at for a in success_attempts)
|
||||
|
||||
email_dt = parse_email_datetime(m.date)
|
||||
received_at = email_dt if email_dt is not None else m.created_at
|
||||
|
||||
return MessageResponse(
|
||||
id=m.id,
|
||||
account_id=m.account_id,
|
||||
@@ -23,7 +38,7 @@ def _build_message_response(m: Message, account_name: str) -> MessageResponse:
|
||||
message_uid=m.message_key,
|
||||
subject=m.subject,
|
||||
sender=m.from_addr,
|
||||
received_at=m.created_at,
|
||||
received_at=received_at,
|
||||
status=m.status.value,
|
||||
error=m.error_message,
|
||||
forwarded_at=forwarded_at,
|
||||
@@ -38,30 +53,138 @@ def _build_message_response(m: Message, account_name: str) -> MessageResponse:
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=list[MessageResponse])
|
||||
@router.get("", response_model=MessageListResponse)
|
||||
def list_messages(
|
||||
db: DbSession,
|
||||
_user: CurrentUser,
|
||||
account_id: int | None = Query(default=None),
|
||||
status: str | None = Query(default=None),
|
||||
limit: int = Query(default=100, ge=1, le=500),
|
||||
limit: int = Query(default=50, ge=1, le=500),
|
||||
offset: int = Query(default=0, ge=0),
|
||||
) -> list[MessageResponse]:
|
||||
query = (
|
||||
db.query(Message, Account.name)
|
||||
.join(Account, Message.account_id == Account.id)
|
||||
.order_by(Message.id.desc())
|
||||
)
|
||||
|
||||
if account_id is not None:
|
||||
query = query.filter(Message.account_id == account_id)
|
||||
|
||||
) -> MessageListResponse:
|
||||
status_enum: MessageStatus | None = None
|
||||
if status is not None:
|
||||
try:
|
||||
status_enum = MessageStatus(status)
|
||||
except ValueError:
|
||||
return []
|
||||
query = query.filter(Message.status == status_enum)
|
||||
return MessageListResponse(items=[], total=0, limit=limit, offset=offset)
|
||||
|
||||
rows = query.offset(offset).limit(limit).all()
|
||||
return [_build_message_response(m, name) for m, name in rows]
|
||||
filters = []
|
||||
if account_id is not None:
|
||||
filters.append(Message.account_id == account_id)
|
||||
if status_enum is not None:
|
||||
filters.append(Message.status == status_enum)
|
||||
|
||||
total = db.query(func.count(Message.id)).filter(*filters).scalar() or 0
|
||||
|
||||
rows = (
|
||||
db.query(Message, Account.name)
|
||||
.join(Account, Message.account_id == Account.id)
|
||||
.filter(*filters)
|
||||
.order_by(Message.id.desc())
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
.all()
|
||||
)
|
||||
|
||||
return MessageListResponse(
|
||||
items=[_build_message_response(m, name) for m, name in rows],
|
||||
total=total,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/queue/status")
|
||||
def queue_status(db: DbSession, _user: CurrentUser) -> dict:
|
||||
return get_queue_status(db)
|
||||
|
||||
|
||||
@router.post("/queue/process")
|
||||
def queue_process(db: DbSession, _user: CurrentUser) -> dict:
|
||||
"""Process one forward-queue tick (same as the worker job)."""
|
||||
return process_forward_queue(db).as_dict()
|
||||
|
||||
|
||||
@router.post("/requeue-forwarded")
|
||||
def requeue_forwarded(db: DbSession, _user: CurrentUser) -> dict:
|
||||
"""Mark all forwarded messages as failed for gradual queue resend."""
|
||||
count = requeue_forwarded_messages(db)
|
||||
status = get_queue_status(db)
|
||||
return {"requeued": count, **status}
|
||||
|
||||
|
||||
@router.post("/retry-batch")
|
||||
def retry_batch(
|
||||
db: DbSession,
|
||||
_user: CurrentUser,
|
||||
limit: int = Query(default=5, ge=1, le=100),
|
||||
account_id: int | None = Query(default=None),
|
||||
all_failed: bool = Query(default=False, alias="all"),
|
||||
) -> dict:
|
||||
"""Retry failed messages via the forward queue (never bulk SMTP).
|
||||
|
||||
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:
|
||||
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 {
|
||||
"queued": False,
|
||||
"errors": [],
|
||||
**result.as_dict(),
|
||||
}
|
||||
|
||||
|
||||
@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")
|
||||
|
||||
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:
|
||||
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)
|
||||
@@ -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,
|
||||
)
|
||||
@@ -145,6 +145,13 @@ class MessageResponse(BaseModel):
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class MessageListResponse(BaseModel):
|
||||
items: list[MessageResponse]
|
||||
total: int
|
||||
limit: int
|
||||
offset: int
|
||||
|
||||
|
||||
class SyncRunResponse(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@ class Settings(BaseSettings):
|
||||
admin_username: str = "admin"
|
||||
admin_password: str = "change-me"
|
||||
sync_interval_minutes: int = 15
|
||||
max_forwards_per_hour: int = 200
|
||||
forward_queue_batch_size: int = 5
|
||||
forward_queue_interval_seconds: int = 60
|
||||
api_host: str = "0.0.0.0"
|
||||
api_port: int = 8000
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -3,8 +3,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import email
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from email.header import decode_header, make_header
|
||||
from email.message import EmailMessage
|
||||
from email.utils import parsedate_to_datetime
|
||||
|
||||
DEFAULT_ALLOWED_EXTENSIONS = {".pdf", ".xml", ".zip"}
|
||||
|
||||
@@ -44,6 +48,19 @@ def normalize_message_id(message_id: str | None) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def parse_email_datetime(date_header: str | None) -> datetime | None:
|
||||
"""Parse RFC2822 Date header to timezone-aware datetime."""
|
||||
if not date_header or not date_header.strip():
|
||||
return None
|
||||
try:
|
||||
dt = parsedate_to_datetime(date_header.strip())
|
||||
except (TypeError, ValueError, IndexError, OverflowError):
|
||||
return None
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
return dt
|
||||
|
||||
|
||||
def get_message_key(folder: str, uid: bytes | str, msg: email.message.EmailMessage) -> str:
|
||||
msg_id = normalize_message_id(msg.get("Message-ID"))
|
||||
if msg_id:
|
||||
@@ -96,8 +113,6 @@ def attachment_allowed(
|
||||
|
||||
filename = part_filename(part)
|
||||
if filename:
|
||||
import os
|
||||
|
||||
_, ext = os.path.splitext(filename)
|
||||
if ext in allowed_extensions:
|
||||
return True
|
||||
@@ -106,6 +121,71 @@ def attachment_allowed(
|
||||
return content_type in ALLOWED_MIME_TYPES
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InvoiceAttachment:
|
||||
filename: str
|
||||
data: bytes
|
||||
maintype: str
|
||||
subtype: str
|
||||
|
||||
|
||||
def _split_content_type(content_type: str) -> tuple[str, str]:
|
||||
maintype, _, subtype = content_type.partition("/")
|
||||
if not subtype:
|
||||
return "application", "octet-stream"
|
||||
return maintype, subtype
|
||||
|
||||
|
||||
def collect_matching_attachments(
|
||||
msg: EmailMessage,
|
||||
*,
|
||||
include_all_attachments: bool = False,
|
||||
allowed_extensions: set[str] | None = None,
|
||||
) -> list[InvoiceAttachment]:
|
||||
"""Extract invoice attachments (PDF/XML/ZIP) from a message for SMTP relay."""
|
||||
if allowed_extensions is None:
|
||||
allowed_extensions = DEFAULT_ALLOWED_EXTENSIONS
|
||||
|
||||
collected: list[InvoiceAttachment] = []
|
||||
seen_names: set[str] = set()
|
||||
|
||||
for part in msg.walk():
|
||||
if part.is_multipart():
|
||||
continue
|
||||
if not attachment_allowed(
|
||||
part,
|
||||
include_all_attachments=include_all_attachments,
|
||||
allowed_extensions=allowed_extensions,
|
||||
):
|
||||
continue
|
||||
|
||||
payload = part.get_payload(decode=True)
|
||||
if not payload:
|
||||
continue
|
||||
|
||||
filename = part_filename(part) or part.get_filename() or ""
|
||||
filename = clean_header(filename) or "attachment"
|
||||
if filename in seen_names:
|
||||
base, ext = os.path.splitext(filename)
|
||||
counter = 2
|
||||
while f"{base}-{counter}{ext}" in seen_names:
|
||||
counter += 1
|
||||
filename = f"{base}-{counter}{ext}"
|
||||
|
||||
seen_names.add(filename)
|
||||
maintype, subtype = _split_content_type(part.get_content_type())
|
||||
collected.append(
|
||||
InvoiceAttachment(
|
||||
filename=filename,
|
||||
data=payload,
|
||||
maintype=maintype,
|
||||
subtype=subtype,
|
||||
)
|
||||
)
|
||||
|
||||
return collected
|
||||
|
||||
|
||||
def has_matching_attachment(
|
||||
msg: EmailMessage,
|
||||
*,
|
||||
|
||||
@@ -4,9 +4,14 @@ from __future__ import annotations
|
||||
|
||||
import smtplib
|
||||
from dataclasses import dataclass
|
||||
from email import policy
|
||||
from email.message import EmailMessage
|
||||
|
||||
from forwarder.email.parsing import (
|
||||
DEFAULT_ALLOWED_EXTENSIONS,
|
||||
clean_subject,
|
||||
collect_matching_attachments,
|
||||
)
|
||||
|
||||
|
||||
DEFAULT_SMTP_TIMEOUT = 30
|
||||
CONNECTION_TEST_SMTP_TIMEOUT = 5
|
||||
@@ -35,38 +40,74 @@ def create_smtp_client(
|
||||
return client
|
||||
|
||||
|
||||
def forward_email_as_eml(
|
||||
def build_forward_message(
|
||||
original_msg: EmailMessage,
|
||||
*,
|
||||
smtp_config: SmtpConfig,
|
||||
from_addr: str,
|
||||
destination_email: str,
|
||||
smtp: smtplib.SMTP | None = None,
|
||||
) -> None:
|
||||
from forwarder.email.parsing import clean_subject
|
||||
include_all_attachments: bool = False,
|
||||
allowed_extensions: set[str] | None = None,
|
||||
) -> EmailMessage:
|
||||
"""Build a clean outbound message with invoice files only.
|
||||
|
||||
Does not relay the original RFC822 (avoids spam filters, loops, and MailChannels
|
||||
blocks on inherited bulk-mail headers). Keeps the original subject without Fwd:.
|
||||
"""
|
||||
if allowed_extensions is None:
|
||||
allowed_extensions = DEFAULT_ALLOWED_EXTENSIONS
|
||||
|
||||
attachments = collect_matching_attachments(
|
||||
original_msg,
|
||||
include_all_attachments=include_all_attachments,
|
||||
allowed_extensions=allowed_extensions,
|
||||
)
|
||||
if not attachments:
|
||||
raise ValueError("No matching invoice attachments to forward")
|
||||
|
||||
subject = clean_subject(original_msg.get("Subject"))
|
||||
sender = original_msg.get("From", "")
|
||||
date = original_msg.get("Date", "")
|
||||
|
||||
fwd = EmailMessage()
|
||||
fwd["From"] = smtp_config.user
|
||||
fwd["To"] = destination_email
|
||||
fwd["Subject"] = f"FWD BizDocs: {subject}"
|
||||
outbound = EmailMessage()
|
||||
outbound["From"] = from_addr
|
||||
outbound["To"] = destination_email
|
||||
outbound["Subject"] = subject
|
||||
|
||||
body = (
|
||||
"Forwarded automatically to BizDocs.\n\n"
|
||||
f"Original From: {sender}\n"
|
||||
f"Original Date: {date}\n"
|
||||
f"Original Subject: {subject}\n"
|
||||
"Documento reencaminhado para arquivo digital.\n\n"
|
||||
f"Remetente original: {sender}\n"
|
||||
f"Data original: {date}\n"
|
||||
f"Assunto original: {subject}\n"
|
||||
f"Anexos: {', '.join(a.filename for a in attachments)}\n"
|
||||
)
|
||||
fwd.set_content(body)
|
||||
outbound.set_content(body)
|
||||
|
||||
raw_bytes = original_msg.as_bytes(policy=policy.default)
|
||||
fwd.add_attachment(
|
||||
raw_bytes,
|
||||
maintype="message",
|
||||
subtype="rfc822",
|
||||
filename="original-email.eml",
|
||||
for attachment in attachments:
|
||||
outbound.add_attachment(
|
||||
attachment.data,
|
||||
maintype=attachment.maintype,
|
||||
subtype=attachment.subtype,
|
||||
filename=attachment.filename,
|
||||
)
|
||||
|
||||
return outbound
|
||||
|
||||
|
||||
def forward_invoice_attachments(
|
||||
original_msg: EmailMessage,
|
||||
*,
|
||||
smtp_config: SmtpConfig,
|
||||
destination_email: str,
|
||||
smtp: smtplib.SMTP | None = None,
|
||||
include_all_attachments: bool = False,
|
||||
allowed_extensions: set[str] | None = None,
|
||||
) -> None:
|
||||
outbound = build_forward_message(
|
||||
original_msg,
|
||||
from_addr=smtp_config.user,
|
||||
destination_email=destination_email,
|
||||
include_all_attachments=include_all_attachments,
|
||||
allowed_extensions=allowed_extensions,
|
||||
)
|
||||
|
||||
owns_client = smtp is None
|
||||
@@ -75,7 +116,11 @@ def forward_email_as_eml(
|
||||
client = create_smtp_client(smtp_config)
|
||||
|
||||
try:
|
||||
client.send_message(fwd)
|
||||
client.send_message(
|
||||
outbound,
|
||||
from_addr=smtp_config.user,
|
||||
to_addrs=[destination_email],
|
||||
)
|
||||
finally:
|
||||
if owns_client:
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Background forward queue — drains failed messages within rate limits."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from forwarder.config import get_settings
|
||||
from forwarder.db.models import Message, MessageStatus
|
||||
from forwarder.services.rate_limit import (
|
||||
ForwardRateLimitError,
|
||||
check_forward_allowed,
|
||||
count_forwards_last_hour,
|
||||
forwards_remaining_this_hour,
|
||||
)
|
||||
from forwarder.services.sync_service import (
|
||||
MessageMissingFromMailboxError,
|
||||
retry_single_message,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ForwardQueueResult:
|
||||
attempted: int = 0
|
||||
succeeded: int = 0
|
||||
failed: int = 0
|
||||
rate_limited: bool = False
|
||||
pending_total: int = 0
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return {
|
||||
"attempted": self.attempted,
|
||||
"succeeded": self.succeeded,
|
||||
"failed": self.failed,
|
||||
"rate_limited": self.rate_limited,
|
||||
"pending_total": self.pending_total,
|
||||
}
|
||||
|
||||
|
||||
def count_queue_pending(db: Session) -> int:
|
||||
return (
|
||||
db.query(Message)
|
||||
.filter(Message.status == MessageStatus.failed)
|
||||
.count()
|
||||
)
|
||||
|
||||
|
||||
def get_queue_status(db: Session) -> dict:
|
||||
settings = get_settings()
|
||||
pending = count_queue_pending(db)
|
||||
used = count_forwards_last_hour(db)
|
||||
remaining = forwards_remaining_this_hour(db)
|
||||
batch = settings.forward_queue_batch_size
|
||||
per_hour = settings.max_forwards_per_hour
|
||||
eta_hours = None
|
||||
if pending > 0 and per_hour > 0:
|
||||
eta_hours = round(pending / per_hour, 1)
|
||||
|
||||
return {
|
||||
"pending": pending,
|
||||
"forwards_used_last_hour": used,
|
||||
"forwards_remaining_this_hour": remaining,
|
||||
"max_forwards_per_hour": per_hour,
|
||||
"batch_size_per_tick": batch,
|
||||
"tick_interval_seconds": settings.forward_queue_interval_seconds,
|
||||
"eta_hours_at_limit": eta_hours,
|
||||
}
|
||||
|
||||
|
||||
def requeue_forwarded_messages(db: Session) -> int:
|
||||
"""Mark forwarded messages as failed so the queue re-sends them."""
|
||||
rows = (
|
||||
db.query(Message)
|
||||
.filter(Message.status == MessageStatus.forwarded)
|
||||
.all()
|
||||
)
|
||||
for message in rows:
|
||||
message.status = MessageStatus.failed
|
||||
message.error_message = None
|
||||
db.commit()
|
||||
logger.info("Requeued %s forwarded message(s) for resend", len(rows))
|
||||
return len(rows)
|
||||
|
||||
|
||||
def process_forward_queue(db: Session) -> ForwardQueueResult:
|
||||
"""Send up to batch_size failed messages, respecting the hourly cap."""
|
||||
settings = get_settings()
|
||||
result = ForwardQueueResult(pending_total=count_queue_pending(db))
|
||||
|
||||
if result.pending_total == 0:
|
||||
return result
|
||||
|
||||
remaining = forwards_remaining_this_hour(db)
|
||||
if remaining is not None and remaining <= 0:
|
||||
result.rate_limited = True
|
||||
logger.info("Forward queue idle: hourly limit reached (%s/h)", settings.max_forwards_per_hour)
|
||||
return result
|
||||
|
||||
batch_limit = settings.forward_queue_batch_size
|
||||
if remaining is not None:
|
||||
batch_limit = min(batch_limit, remaining)
|
||||
|
||||
messages = (
|
||||
db.query(Message)
|
||||
.filter(Message.status == MessageStatus.failed)
|
||||
.order_by(Message.id.asc())
|
||||
.limit(batch_limit)
|
||||
.all()
|
||||
)
|
||||
|
||||
for message in messages:
|
||||
try:
|
||||
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")
|
||||
break
|
||||
except Exception as exc:
|
||||
result.failed += 1
|
||||
logger.error("Forward queue failed for message %s: %s", message.id, exc)
|
||||
result.attempted += 1
|
||||
|
||||
result.pending_total = count_queue_pending(db)
|
||||
if result.attempted:
|
||||
logger.info(
|
||||
"Forward queue tick: %s ok, %s failed, %s pending",
|
||||
result.succeeded,
|
||||
result.failed,
|
||||
result.pending_total,
|
||||
)
|
||||
return result
|
||||
@@ -0,0 +1,52 @@
|
||||
"""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 forwards_remaining_this_hour(db: Session) -> int | None:
|
||||
settings = get_settings()
|
||||
if settings.max_forwards_per_hour <= 0:
|
||||
return None
|
||||
used = count_forwards_last_hour(db)
|
||||
return max(0, settings.max_forwards_per_hour - used)
|
||||
|
||||
|
||||
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)
|
||||
@@ -29,13 +29,28 @@ from forwarder.email.parsing import (
|
||||
get_message_key,
|
||||
has_matching_attachment,
|
||||
)
|
||||
from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_email_as_eml
|
||||
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__)
|
||||
|
||||
|
||||
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
|
||||
@@ -45,16 +60,11 @@ class SyncResult:
|
||||
self.messages_failed = 0
|
||||
|
||||
|
||||
def _get_processed_keys(db: Session, account_id: int) -> set[str]:
|
||||
def _get_known_message_keys(db: Session, account_id: int) -> set[str]:
|
||||
"""Message-IDs already in DB — sync skips them; retries use the queue."""
|
||||
rows = (
|
||||
db.query(Message.message_key)
|
||||
.filter(
|
||||
Message.account_id == account_id,
|
||||
Message.status.in_([
|
||||
MessageStatus.forwarded,
|
||||
MessageStatus.dry_run,
|
||||
]),
|
||||
)
|
||||
.filter(Message.account_id == account_id)
|
||||
.all()
|
||||
)
|
||||
return {row[0] for row in rows}
|
||||
@@ -159,7 +169,7 @@ def sync_account(
|
||||
)
|
||||
|
||||
allowed_extensions = set(account.allowed_extensions or [])
|
||||
processed_keys = _get_processed_keys(db, account_id)
|
||||
processed_keys = _get_known_message_keys(db, account_id)
|
||||
handled_count = 0
|
||||
stop_all = False
|
||||
|
||||
@@ -256,11 +266,14 @@ def sync_account(
|
||||
continue
|
||||
|
||||
try:
|
||||
forward_email_as_eml(
|
||||
check_forward_allowed(db)
|
||||
forward_invoice_attachments(
|
||||
msg,
|
||||
smtp_config=smtp_config,
|
||||
destination_email=account.destination_email,
|
||||
smtp=smtp,
|
||||
include_all_attachments=account.include_all_attachments,
|
||||
allowed_extensions=allowed_extensions,
|
||||
)
|
||||
message_row = _upsert_message(
|
||||
db,
|
||||
@@ -280,6 +293,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)
|
||||
@@ -312,6 +329,7 @@ def sync_account(
|
||||
dry_run=False,
|
||||
error_message=error_text,
|
||||
)
|
||||
processed_keys.add(message_key)
|
||||
result.messages_failed += 1
|
||||
|
||||
sync_run.status = SyncRunStatus.completed
|
||||
@@ -348,4 +366,128 @@ 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:
|
||||
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")
|
||||
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(
|
||||
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):
|
||||
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:
|
||||
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 [])
|
||||
check_forward_allowed(db)
|
||||
forward_invoice_attachments(
|
||||
msg,
|
||||
smtp_config=smtp_config,
|
||||
destination_email=account.destination_email,
|
||||
smtp=smtp,
|
||||
include_all_attachments=account.include_all_attachments,
|
||||
allowed_extensions=allowed_extensions,
|
||||
)
|
||||
|
||||
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 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)
|
||||
_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
|
||||
@@ -10,12 +10,33 @@ from forwarder.db.session import get_session_factory
|
||||
from forwarder.error_reporter import report_error_with_cooldown
|
||||
from forwarder.services.sync_service import sync_account
|
||||
|
||||
from forwarder.services.forward_queue_service import process_forward_queue
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SCHEDULE_REFRESH_MINUTES = 2
|
||||
FORWARD_QUEUE_JOB_ID = "forward-queue"
|
||||
|
||||
|
||||
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 +53,42 @@ def _sync_job(account_id: int) -> None:
|
||||
db.close()
|
||||
|
||||
|
||||
def run_worker(*, default_interval: int = 15) -> None:
|
||||
scheduler = BlockingScheduler()
|
||||
|
||||
def _forward_queue_job() -> None:
|
||||
db = get_session_factory()()
|
||||
try:
|
||||
process_forward_queue(db)
|
||||
except Exception as exc:
|
||||
logger.exception("Forward queue job failed")
|
||||
report_error_with_cooldown(
|
||||
"scheduler:forward_queue",
|
||||
300.0,
|
||||
exc,
|
||||
severity="error",
|
||||
endpoint="scheduler:forward_queue",
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
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 +96,52 @@ 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:
|
||||
from forwarder.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
scheduler = BlockingScheduler()
|
||||
|
||||
_refresh_account_schedules(scheduler, default_interval=default_interval)
|
||||
|
||||
scheduler.add_job(
|
||||
_forward_queue_job,
|
||||
trigger=IntervalTrigger(seconds=settings.forward_queue_interval_seconds),
|
||||
id=FORWARD_QUEUE_JOB_ID,
|
||||
replace_existing=True,
|
||||
max_instances=1,
|
||||
)
|
||||
logger.info(
|
||||
"Forward queue scheduled every %ss, batch size %s, max %s/hour",
|
||||
settings.forward_queue_interval_seconds,
|
||||
settings.forward_queue_batch_size,
|
||||
settings.max_forwards_per_hour,
|
||||
)
|
||||
|
||||
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,105 @@
|
||||
"""Forward queue service tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from forwarder.db.models import MessageStatus
|
||||
from forwarder.services.forward_queue_service import (
|
||||
get_queue_status,
|
||||
process_forward_queue,
|
||||
requeue_forwarded_messages,
|
||||
)
|
||||
from forwarder.services.rate_limit import ForwardRateLimitError
|
||||
|
||||
|
||||
def test_get_queue_status_includes_eta():
|
||||
db = MagicMock()
|
||||
with patch("forwarder.services.forward_queue_service.get_settings") as settings:
|
||||
settings.return_value.forward_queue_batch_size = 5
|
||||
settings.return_value.forward_queue_interval_seconds = 60
|
||||
settings.return_value.max_forwards_per_hour = 200
|
||||
with patch("forwarder.services.forward_queue_service.count_queue_pending", return_value=400):
|
||||
with patch("forwarder.services.forward_queue_service.count_forwards_last_hour", return_value=10):
|
||||
with patch(
|
||||
"forwarder.services.forward_queue_service.forwards_remaining_this_hour",
|
||||
return_value=190,
|
||||
):
|
||||
status = get_queue_status(db)
|
||||
|
||||
assert status["pending"] == 400
|
||||
assert status["eta_hours_at_limit"] == 2.0
|
||||
assert status["batch_size_per_tick"] == 5
|
||||
|
||||
|
||||
def test_process_queue_respects_batch_size():
|
||||
db = MagicMock()
|
||||
messages = [MagicMock(id=i) for i in (1, 2, 3, 4, 5, 6)]
|
||||
query = MagicMock()
|
||||
query.filter.return_value.order_by.return_value.limit.return_value.all.return_value = messages[:5]
|
||||
db.query.return_value = query
|
||||
|
||||
with patch("forwarder.services.forward_queue_service.get_settings") as settings:
|
||||
settings.return_value.forward_queue_batch_size = 5
|
||||
settings.return_value.max_forwards_per_hour = 200
|
||||
with patch("forwarder.services.forward_queue_service.count_queue_pending", side_effect=[6, 1]):
|
||||
with patch("forwarder.services.forward_queue_service.forwards_remaining_this_hour", return_value=200):
|
||||
with patch("forwarder.services.forward_queue_service.check_forward_allowed"):
|
||||
with patch("forwarder.services.forward_queue_service.retry_single_message"):
|
||||
result = process_forward_queue(db)
|
||||
|
||||
assert result.attempted == 5
|
||||
assert result.succeeded == 5
|
||||
query.filter.return_value.order_by.return_value.limit.assert_called_with(5)
|
||||
|
||||
|
||||
def test_process_queue_stops_at_hourly_limit():
|
||||
db = MagicMock()
|
||||
with patch("forwarder.services.forward_queue_service.get_settings") as settings:
|
||||
settings.return_value.forward_queue_batch_size = 5
|
||||
settings.return_value.max_forwards_per_hour = 200
|
||||
with patch("forwarder.services.forward_queue_service.count_queue_pending", return_value=10):
|
||||
with patch("forwarder.services.forward_queue_service.forwards_remaining_this_hour", return_value=0):
|
||||
result = process_forward_queue(db)
|
||||
|
||||
assert result.rate_limited is True
|
||||
assert result.attempted == 0
|
||||
|
||||
|
||||
def test_process_queue_breaks_on_rate_limit_mid_batch():
|
||||
db = MagicMock()
|
||||
messages = [MagicMock(id=1), MagicMock(id=2)]
|
||||
query = MagicMock()
|
||||
query.filter.return_value.order_by.return_value.limit.return_value.all.return_value = messages
|
||||
db.query.return_value = query
|
||||
|
||||
with patch("forwarder.services.forward_queue_service.get_settings") as settings:
|
||||
settings.return_value.forward_queue_batch_size = 5
|
||||
settings.return_value.max_forwards_per_hour = 200
|
||||
with patch("forwarder.services.forward_queue_service.count_queue_pending", side_effect=[2, 1]):
|
||||
with patch("forwarder.services.forward_queue_service.forwards_remaining_this_hour", return_value=5):
|
||||
with patch(
|
||||
"forwarder.services.forward_queue_service.check_forward_allowed",
|
||||
side_effect=[None, ForwardRateLimitError(limit=200, used=200)],
|
||||
):
|
||||
with patch("forwarder.services.forward_queue_service.retry_single_message"):
|
||||
result = process_forward_queue(db)
|
||||
|
||||
assert result.attempted == 1
|
||||
assert result.succeeded == 1
|
||||
assert result.rate_limited is True
|
||||
|
||||
|
||||
def test_requeue_forwarded_messages():
|
||||
db = MagicMock()
|
||||
msg_a = MagicMock(status=MessageStatus.forwarded, error_message="old")
|
||||
msg_b = MagicMock(status=MessageStatus.forwarded, error_message="old")
|
||||
db.query.return_value.filter.return_value.all.return_value = [msg_a, msg_b]
|
||||
|
||||
count = requeue_forwarded_messages(db)
|
||||
|
||||
assert count == 2
|
||||
assert msg_a.status == MessageStatus.failed
|
||||
assert msg_b.status == MessageStatus.failed
|
||||
assert msg_a.error_message is None
|
||||
db.commit.assert_called_once()
|
||||
@@ -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)
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Email parsing tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from forwarder.email.parsing import parse_email_datetime
|
||||
|
||||
|
||||
def test_parse_email_datetime_valid():
|
||||
dt = parse_email_datetime("Tue, 18 Feb 2025 18:23:09 +0000")
|
||||
assert dt is not None
|
||||
assert dt.year == 2025
|
||||
assert dt.month == 2
|
||||
assert dt.day == 18
|
||||
|
||||
|
||||
def test_parse_email_datetime_invalid():
|
||||
assert parse_email_datetime("") is None
|
||||
assert parse_email_datetime(None) is None
|
||||
assert parse_email_datetime("not-a-date") is None
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Outbound forward sends a clean message with invoice attachments only."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from email.message import EmailMessage
|
||||
|
||||
from forwarder.email.smtp_client import build_forward_message
|
||||
|
||||
|
||||
def test_forward_sends_clean_message_with_pdf_only():
|
||||
original = EmailMessage()
|
||||
original["From"] = "[email protected]"
|
||||
original["To"] = "[email protected]"
|
||||
original["Subject"] = "Invoice & Ticket Delivery"
|
||||
original["X-SG-EID"] = "spam-marker"
|
||||
original.set_content("marketing body")
|
||||
original.add_attachment(
|
||||
b"%PDF-1.4",
|
||||
maintype="application",
|
||||
subtype="pdf",
|
||||
filename="fatura.pdf",
|
||||
)
|
||||
|
||||
outbound = build_forward_message(
|
||||
original,
|
||||
from_addr="[email protected]",
|
||||
destination_email="[email protected]",
|
||||
)
|
||||
|
||||
assert outbound["From"] == "[email protected]"
|
||||
assert outbound["To"] == "[email protected]"
|
||||
assert outbound["Subject"] == "Invoice & Ticket Delivery"
|
||||
assert not outbound["Subject"].lower().startswith("fwd:")
|
||||
assert outbound.get("Cc") is None
|
||||
assert outbound.get("X-SG-EID") is None
|
||||
|
||||
attachments = list(outbound.iter_attachments())
|
||||
assert len(attachments) == 1
|
||||
assert attachments[0].get_filename() == "fatura.pdf"
|
||||
assert attachments[0].get_content_type() == "application/pdf"
|
||||
|
||||
text_parts = [
|
||||
p.get_content()
|
||||
for p in outbound.walk()
|
||||
if not p.is_multipart() and p.get_content_type() == "text/plain"
|
||||
]
|
||||
assert text_parts
|
||||
assert "Remetente original" in text_parts[0]
|
||||
assert "marketing body" not in text_parts[0]
|
||||
|
||||
|
||||
def test_forward_includes_multiple_invoice_types():
|
||||
original = EmailMessage()
|
||||
original["Subject"] = "Docs"
|
||||
original.set_content("x")
|
||||
original.add_attachment(b"%PDF", maintype="application", subtype="pdf", filename="a.pdf")
|
||||
original.add_attachment(b"<x/>", maintype="text", subtype="xml", filename="b.xml")
|
||||
|
||||
outbound = build_forward_message(
|
||||
original,
|
||||
from_addr="[email protected]",
|
||||
destination_email="[email protected]",
|
||||
)
|
||||
|
||||
names = {p.get_filename() for p in outbound.iter_attachments()}
|
||||
assert names == {"a.pdf", "b.xml"}
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-off: list duplicate failed messages in DB."""
|
||||
from collections import Counter, defaultdict
|
||||
|
||||
from forwarder.db.models import Message, MessageStatus
|
||||
from forwarder.db.session import get_session_factory
|
||||
|
||||
|
||||
def main() -> None:
|
||||
db = get_session_factory()()
|
||||
rows = (
|
||||
db.query(
|
||||
Message.id,
|
||||
Message.subject,
|
||||
Message.from_addr,
|
||||
Message.date,
|
||||
Message.folder,
|
||||
Message.uid,
|
||||
Message.message_key,
|
||||
)
|
||||
.filter(Message.status == MessageStatus.failed)
|
||||
.all()
|
||||
)
|
||||
by_triple: Counter[tuple[str, str, str]] = Counter()
|
||||
detail: dict[tuple[str, str, str], list[tuple[int, str, str, str]]] = defaultdict(list)
|
||||
for mid, subject, from_addr, date, folder, uid, message_key in rows:
|
||||
key = (subject or "", from_addr or "", date or "")
|
||||
by_triple[key] += 1
|
||||
detail[key].append((mid, folder, uid, message_key))
|
||||
|
||||
dups = [(k, v) for k, v in by_triple.items() if v > 1]
|
||||
print(f"failed_total={len(rows)} duplicate_groups={len(dups)}")
|
||||
for (subject, from_addr, date), count in sorted(dups, key=lambda x: -x[1])[:10]:
|
||||
print(f"\n--- count={count} subject={subject[:60]!r} date={date}")
|
||||
for mid, folder, uid, message_key in detail[(subject, from_addr, date)][:6]:
|
||||
print(f" id={mid} folder={folder!r} uid={uid} key={message_key[:80]}")
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user