worker.go161 lines, 5.3 KB
| 1 | package webhook |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "log/slog" |
| 10 | "math/rand/v2" |
| 11 | "net/http" |
| 12 | "sync" |
| 13 | "time" |
| 14 | |
| 15 | "github.com/fiston-user/payments/internal/webhook/signature" |
| 16 | "github.com/fiston-user/payments/internal/webhook/webhookdb" |
| 17 | "github.com/prometheus/client_golang/prometheus" |
| 18 | "github.com/prometheus/client_golang/prometheus/promauto" |
| 19 | ) |
| 20 | |
| 21 | // Schedule is how long we wait before each retry: a day and a bit, in all, so |
| 22 | // a receiver that's down overnight still gets everything. |
| 23 | var Schedule = []time.Duration{ |
| 24 | 5 * time.Second, 5 * time.Minute, 30 * time.Minute, |
| 25 | 2 * time.Hour, 5 * time.Hour, 10 * time.Hour, 10 * time.Hour, |
| 26 | } |
| 27 | |
| 28 | var attempts = promauto.NewCounterVec(prometheus.CounterOpts{ |
| 29 | Name: "webhook_attempts_total", |
| 30 | Help: "Webhook delivery attempts, by what happened next: succeeded, pending or failed.", |
| 31 | }, []string{"state"}) |
| 32 | |
| 33 | // batchSize is how many deliveries a worker claims, and sends, at once. |
| 34 | const batchSize = 20 |
| 35 | |
| 36 | // A Worker sends due deliveries, and writes down how each attempt went. |
| 37 | type Worker struct { |
| 38 | q *webhookdb.Queries |
| 39 | client *http.Client |
| 40 | logger *slog.Logger |
| 41 | Schedule []time.Duration // the wait before each retry: after the last, we give up |
| 42 | wake chan struct{} |
| 43 | } |
| 44 | |
| 45 | // NewWorker returns a Worker that sends with client. |
| 46 | func NewWorker(q *webhookdb.Queries, client *http.Client, logger *slog.Logger) *Worker { |
| 47 | return &Worker{q: q, client: client, logger: logger, Schedule: Schedule, wake: make(chan struct{}, 1)} |
| 48 | } |
| 49 | |
| 50 | // Wake makes the worker look for due deliveries now, instead of in a second. |
| 51 | func (w *Worker) Wake() { |
| 52 | select { |
| 53 | case w.wake <- struct{}{}: |
| 54 | default: // a wake-up is already waiting |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | // Run sends deliveries until ctx is canceled: whenever it's woken up, and |
| 59 | // every second, for retries that come due. |
| 60 | func (w *Worker) Run(ctx context.Context) { |
| 61 | w.logger.Info("webhook worker started", "schedule", w.Schedule) |
| 62 | tick := time.NewTicker(time.Second) |
| 63 | defer tick.Stop() |
| 64 | for { |
| 65 | n, err := w.DeliverDue(ctx) |
| 66 | if err != nil && ctx.Err() == nil { |
| 67 | w.logger.Warn("deliver webhooks", "err", err) |
| 68 | } |
| 69 | if n == batchSize { |
| 70 | continue // there may be more, right now |
| 71 | } |
| 72 | select { |
| 73 | case <-ctx.Done(): |
| 74 | return |
| 75 | case <-w.wake: |
| 76 | case <-tick.C: |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | // DeliverDue claims the deliveries that are due, sends them all at once, and |
| 82 | // returns how many there were. |
| 83 | func (w *Worker) DeliverDue(ctx context.Context) (int, error) { |
| 84 | due, err := w.q.ClaimDue(ctx, batchSize) |
| 85 | if err != nil { |
| 86 | return 0, fmt.Errorf("claim deliveries: %w", err) |
| 87 | } |
| 88 | // A claimed batch is sent, and written down, even while we shut down: |
| 89 | // otherwise it waits for its lease to run out. |
| 90 | ctx = context.WithoutCancel(ctx) |
| 91 | var wg sync.WaitGroup |
| 92 | for _, d := range due { |
| 93 | wg.Go(func() { w.deliver(ctx, d) }) |
| 94 | } |
| 95 | wg.Wait() |
| 96 | return len(due), nil |
| 97 | } |
| 98 | |
| 99 | // deliver makes one attempt, and records it: done, retry later, or give up. |
| 100 | func (w *Worker) deliver(ctx context.Context, d webhookdb.ClaimDueRow) { |
| 101 | start := time.Now() |
| 102 | status, err := w.send(ctx, d) |
| 103 | attempt := webhookdb.RecordAttemptParams{ |
| 104 | ID: d.ID, State: "succeeded", LastStatus: int32(status), |
| 105 | LastResponseMs: int32(time.Since(start).Milliseconds()), |
| 106 | } |
| 107 | log := w.logger.With("delivery", d.ID, "attempt", d.Attempts+1, "status", status) |
| 108 | if err != nil { |
| 109 | attempt.LastError = err.Error() |
| 110 | attempt.State, attempt.RetryInSeconds = w.retry(int(d.Attempts) + 1) |
| 111 | log.Warn("webhook failed", "state", attempt.State, "retry_in_s", attempt.RetryInSeconds, "err", err) |
| 112 | } else { |
| 113 | log.Info("webhook delivered", "ms", attempt.LastResponseMs) |
| 114 | } |
| 115 | attempts.WithLabelValues(attempt.State).Inc() |
| 116 | if err := w.q.RecordAttempt(ctx, attempt); err != nil { |
| 117 | log.Error("record attempt", "err", err) // the lease runs out, and it's sent again |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | // retry says what happens after a failed attempt: another one, so many |
| 122 | // seconds from now, or none. |
| 123 | func (w *Worker) retry(attempts int) (string, float64) { |
| 124 | if attempts > len(w.Schedule) { |
| 125 | return "failed", 0 |
| 126 | } |
| 127 | // Up to a tenth more, at random: when a receiver comes back, its retries |
| 128 | // arrive spread out, instead of all at once. |
| 129 | wait := w.Schedule[attempts-1] |
| 130 | wait += rand.N(wait/10 + 1) |
| 131 | return "pending", wait.Round(time.Millisecond).Seconds() |
| 132 | } |
| 133 | |
| 134 | // send POSTs a delivery, signed. Any 2xx is a success, anything else a failure. |
| 135 | func (w *Worker) send(ctx context.Context, d webhookdb.ClaimDueRow) (int, error) { |
| 136 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, d.URL, bytes.NewReader(d.Payload)) |
| 137 | if err != nil { |
| 138 | return 0, err |
| 139 | } |
| 140 | // The event's ID: the same on every retry, and every replay, so the |
| 141 | // receiver can tell it has seen this one before. |
| 142 | err = signature.Sign(req.Header, d.Secret, d.EventID.String(), time.Now(), d.Payload) |
| 143 | if err != nil { |
| 144 | return 0, err |
| 145 | } |
| 146 | req.Header.Set("Content-Type", "application/json") |
| 147 | req.Header.Set("User-Agent", "payments-webhooks/1") |
| 148 | resp, err := w.client.Do(req) |
| 149 | if err != nil { |
| 150 | // Do's errors are *url.Error: the method and the URL, which the |
| 151 | // merchant knows, around what actually went wrong. |
| 152 | return 0, errors.Unwrap(err) |
| 153 | } |
| 154 | defer resp.Body.Close() |
| 155 | // Read a little of the body, so the connection can be reused, but never all of it. |
| 156 | io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10)) |
| 157 | if resp.StatusCode < 200 || resp.StatusCode > 299 { |
| 158 | return resp.StatusCode, fmt.Errorf("receiver answered %s", resp.Status) |
| 159 | } |
| 160 | return resp.StatusCode, nil |
| 161 | } |