fix(qa-weekly-mail): 修复发送记录读回并区分未知投递
build / build (push) Successful in 2m18s

1) 发送记录读回(确定性回归):Sends() 的 SELECT 只有 6 列,Scan 却收 7 个字段(多出
message_id)。只要历史里存在任意一条发送记录,整个列表就返回 ErrUnavailable —— 发送
成功后页面刷新、以及“完成读真实发送记录”都会失败。改为查询带 message_id,并检查
rows.Err(),不把截断的列表当成完整历史。

2) 未知投递不再当成可重试失败:DATA 已提交但没收到最终 250(连接中断/超时)时,邮件可能
已被服务器接受;旧实现记 failed 并允许下一分钟重发,会重复投递。现在由 SMTPMailer 在
writer.Close() 失败处抛出窄类型 unknownDeliveryError,deliver 保留 sending 并记录原因,
自动/手动路径都不再重发(手动返回 ERRDeliveryUnknown,HTTP 409 说明原因)。连接建立前
失败、STARTTLS/AUTH/MAIL/RCPT/DATA 命令被拒、正文写入失败仍是确定失败,可如实 failed 并
重试一次。

3) SMTP 交互加有限期限:整体 90 秒(随请求 ctx 收紧),并用 context.AfterFunc 在取消时打断
阻塞读写,避免服务器接受 DATA 后不响应时挂死 worker 与发送行。

验证:真实隔离 PG 先 RED 后 GREEN(非空 sent+failed 历史读回成功并带真实 message_id;
HTTP GET /weekly-mail/sends 非空历史 200);本机 TLS SMTP 桩 + 真实 SMTPMailer 覆盖成功、
RCPT 550、DATA 后丢最终 250、DATA 阶段卡死(ctx 800ms 内返回)四类;真实 deliver 在未知
结果时留 sending 且不重发,在明确拒绝时 failed 并可重试一次成功。make verify 17 项全绿。
This commit is contained in:
姚章浩
2026-11-09 01:06:09 +08:00
parent 719876d039
commit 5e850e96f5
10 changed files with 690 additions and 11 deletions
+72 -7
View File
@@ -36,8 +36,25 @@ var (
ErrSlotPending = errors.New("weekly mail slot has not arrived for the running week")
ErrNotConfigured = errors.New("weekly mail transport is not configured")
ErrSendInFlight = errors.New("weekly mail send outcome is unknown")
// ErrDeliveryUnknown is the honest answer when the SMTP exchange ended without a final
// verdict: the server may already have queued the message, so retrying could duplicate it.
ErrDeliveryUnknown = errors.New("weekly mail delivery outcome is unknown")
)
// unknownDeliveryError marks a failure where the server may already have accepted the message.
// Only the caller that knows the SMTP phase can raise it, so a plain I/O error never silently
// becomes "unknown" (and never silently becomes a retryable failure either).
type unknownDeliveryError struct{ err error }
func (e *unknownDeliveryError) Error() string { return e.err.Error() }
func (e *unknownDeliveryError) Unwrap() error { return e.err }
// IsUnknownDelivery reports whether the send may have reached the recipients.
func IsUnknownDelivery(err error) bool {
var unknown *unknownDeliveryError
return errors.As(err, &unknown)
}
// Settings never carries the SMTP password; HasPassword only says whether one is stored.
type Settings struct {
Host string `json:"host"`
@@ -414,7 +431,7 @@ func (s *Store) Sends(ctx context.Context, week string) ([]Send, error) {
if !s.valid() {
return nil, ErrUnavailable
}
rows, err := s.pool.Query(ctx, `SELECT week,draft_revision,status,attempts,last_error,updated_at FROM qa_weekly_email_sends WHERE tenant_key=$1 AND ($2='' OR week=$2) ORDER BY updated_at DESC LIMIT 50`, s.tenant, week)
rows, err := s.pool.Query(ctx, `SELECT week,draft_revision,status,attempts,last_error,message_id,updated_at FROM qa_weekly_email_sends WHERE tenant_key=$1 AND ($2='' OR week=$2) ORDER BY updated_at DESC LIMIT 50`, s.tenant, week)
if err != nil {
return nil, ErrUnavailable
}
@@ -427,6 +444,10 @@ func (s *Store) Sends(ctx context.Context, week string) ([]Send, error) {
}
out = append(out, item)
}
// A read that stopped early is not a successful list: callers would silently show partial history.
if err := rows.Err(); err != nil {
return nil, ErrUnavailable
}
return out, nil
}
@@ -653,6 +674,12 @@ func (s *Store) deliver(ctx context.Context, settings Settings, week string, rev
if len(reason) > 400 {
reason = reason[:400]
}
if IsUnknownDelivery(sendErr) {
// The message may already be queued at the server. Leaving the row in 'sending' makes
// every later attempt (automatic or manual) refuse instead of blindly re-delivering.
_, _ = s.pool.Exec(ctx, `UPDATE qa_weekly_email_sends SET last_error=$2,updated_at=now() WHERE id=$1`, sendID, reason)
return delivery{state: "unknown", reason: "SMTP 已提交但未收到最终确认,投递结果未知;为避免重复已停止自动重发,请核对已发出的邮件:" + reason}, nil
}
_, _ = s.pool.Exec(ctx, `UPDATE qa_weekly_email_sends SET status='failed',last_error=$2,updated_at=now() WHERE id=$1`, sendID, reason)
return delivery{state: "failed", reason: "发送失败:" + reason}, nil
}
@@ -804,6 +831,8 @@ func (s *Store) SendManual(ctx context.Context, week string, revision int64, has
return out, ErrNoPassword
case "in_flight":
return out, ErrSendInFlight
case "unknown":
return out, ErrDeliveryUnknown
}
return out, nil
}
@@ -849,24 +878,56 @@ table{border-collapse:collapse}h1:first-child{margin-top:0}
}
// SMTPMailer speaks SMTP directly: implicit TLS on 465, STARTTLS elsewhere. Plaintext is refused.
type SMTPMailer struct{}
// TLS is nil in production (system roots); an in-process test stub injects its own trust so the
// real mailer — not a mock — can be exercised end to end.
type SMTPMailer struct{ TLS *tls.Config }
func (SMTPMailer) Send(ctx context.Context, cfg SMTPConfig, msg Message) (string, error) {
// smtpExchangeTimeout bounds the whole SMTP conversation. Without it a server that accepts DATA
// and then stops responding would hang the worker (and hold the send row) indefinitely.
const smtpExchangeTimeout = 90 * time.Second
func (m SMTPMailer) tlsConfig(host string) *tls.Config {
cfg := &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}
if m.TLS != nil {
cfg = m.TLS.Clone()
if cfg.ServerName == "" {
cfg.ServerName = host
}
if cfg.MinVersion == 0 {
cfg.MinVersion = tls.VersionTLS12
}
}
return cfg
}
func (m SMTPMailer) Send(ctx context.Context, cfg SMTPConfig, msg Message) (string, error) {
if cfg.Host == "" || cfg.Port <= 0 || len(msg.To) == 0 || !validAddress(msg.From) {
return "", ErrInvalid
}
deadline := time.Now().Add(smtpExchangeTimeout)
if ctxDeadline, ok := ctx.Deadline(); ok && ctxDeadline.Before(deadline) {
deadline = ctxDeadline
}
address := net.JoinHostPort(cfg.Host, fmt.Sprint(cfg.Port))
dialer := &net.Dialer{Timeout: 15 * time.Second}
dialer := &net.Dialer{Timeout: 15 * time.Second, Deadline: deadline}
var conn net.Conn
var err error
if cfg.Port == 465 {
conn, err = tls.DialWithDialer(dialer, "tcp", address, &tls.Config{ServerName: cfg.Host, MinVersion: tls.VersionTLS12})
conn, err = tls.DialWithDialer(dialer, "tcp", address, m.tlsConfig(cfg.Host))
} else {
conn, err = dialer.DialContext(ctx, "tcp", address)
}
if err != nil {
// The connection never opened: nothing was submitted, so this is a retryable failure.
return "", fmt.Errorf("smtp 连接失败: %w", err)
}
if err := conn.SetDeadline(deadline); err != nil {
conn.Close()
return "", fmt.Errorf("smtp 设置超时失败: %w", err)
}
// Cancellation must interrupt a blocked read/write, not just the dial.
stop := context.AfterFunc(ctx, func() { _ = conn.SetDeadline(time.Now()) })
defer stop()
client, err := smtp.NewClient(conn, cfg.Host)
if err != nil {
conn.Close()
@@ -877,7 +938,7 @@ func (SMTPMailer) Send(ctx context.Context, cfg SMTPConfig, msg Message) (string
if ok, _ := client.Extension("STARTTLS"); !ok {
return "", errors.New("smtp 服务器不支持 STARTTLS,已拒绝明文发送")
}
if err := client.StartTLS(&tls.Config{ServerName: cfg.Host, MinVersion: tls.VersionTLS12}); err != nil {
if err := client.StartTLS(m.tlsConfig(cfg.Host)); err != nil {
return "", fmt.Errorf("smtp STARTTLS 失败: %w", err)
}
}
@@ -901,10 +962,14 @@ func (SMTPMailer) Send(ctx context.Context, cfg SMTPConfig, msg Message) (string
messageID := fmt.Sprintf("<%s@%s>", hex.EncodeToString(randomBytes(12)), domainOf(msg.From))
boundary := hex.EncodeToString(randomBytes(10))
if _, err = writer.Write([]byte(buildMIME(msg, messageID, boundary))); err != nil {
// The body never finished uploading, so the server cannot have accepted it.
return "", fmt.Errorf("smtp 写入失败: %w", err)
}
if err = writer.Close(); err != nil {
return "", fmt.Errorf("smtp 提交失败: %w", err)
// Close() sends the terminating "." and waits for the final 250. Losing that exchange
// (dropped connection, timeout) means the message may already be queued: it must stay
// unknown rather than be retried as a plain failure.
return "", &unknownDeliveryError{err: fmt.Errorf("smtp 提交后未收到最终确认: %w", err)}
}
_ = client.Quit()
return messageID, nil