Files
dobotai-platform/internal/coverage/dispatcher.go
2026-07-22 12:36:33 +08:00

64 lines
1.9 KiB
Go

package coverage
import (
"context"
"fmt"
"time"
)
const (
// FailureCodeDingtalkGroupSendFailed is the stable failure code used when
// a dingtalk group send fails. Raw errors must never be persisted.
FailureCodeDingtalkGroupSendFailed = "dingtalk_group_send_failed"
)
// RunOnce claims a batch of pending support cases and sends each one via the
// Notifier. The parent context is checked before the claim. Each item gets a
// per-item timeout derived from d.SendTimeout. On success, the item is marked
// notified; on failure, it is marked with a stable failure code — raw errors
// are never persisted. Mark/Claim infrastructure errors are returned with
// stable wrapping. An empty batch is a successful no-op.
func (d *Dispatcher) RunOnce(ctx context.Context) (DispatcherStats, error) {
if err := ctx.Err(); err != nil {
return DispatcherStats{}, err
}
staleBefore := time.Now().Add(-d.ClaimLease)
cases, err := d.repo.Claim(ctx, d.BatchSize, d.MaxAttempts, staleBefore)
if err != nil {
return DispatcherStats{}, fmt.Errorf("dispatcher claim: %w", err)
}
stats := DispatcherStats{Claimed: len(cases)}
if stats.Claimed == 0 {
return stats, nil
}
for _, sc := range cases {
// Check parent context before each item.
if err := ctx.Err(); err != nil {
return stats, err
}
sendCtx, cancel := context.WithTimeout(ctx, d.SendTimeout)
sendErr := d.notifier.Send(sendCtx, sc.SupportNotification)
cancel()
if sendErr != nil {
// Only persist the stable failure code, never the raw error.
if err := d.repo.MarkFailed(ctx, sc.CaseID, FailureCodeDingtalkGroupSendFailed); err != nil {
return stats, fmt.Errorf("dispatcher mark failed: %w", err)
}
stats.Failed++
continue
}
if err := d.repo.MarkNotified(ctx, sc.CaseID); err != nil {
return stats, fmt.Errorf("dispatcher mark notified: %w", err)
}
stats.Notified++
}
return stats, nil
}