Skip to content

Commit

Permalink
Tweak error handling and de-pointer timeout field.
Browse files Browse the repository at this point in the history
Signed-off-by: Steve Simpson <[email protected]>
  • Loading branch information
stevesg committed Nov 29, 2024
1 parent b6d1f67 commit e731915
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 9 deletions.
5 changes: 3 additions & 2 deletions config/notifiers.go
Original file line number Diff line number Diff line change
Expand Up @@ -536,8 +536,9 @@ type WebhookConfig struct {
// allows an unlimited number of alerts.
MaxAlerts uint64 `yaml:"max_alerts" json:"max_alerts"`

// Timeout is the maximum time allowed to invoke the webhook.
Timeout *time.Duration `yaml:"timeout" json:"timeout"`
// Timeout is the maximum time allowed to invoke the webhook. Setting this to 0
// does not impose a timeout.
Timeout time.Duration `yaml:"timeout" json:"timeout"`
}

// UnmarshalYAML implements the yaml.Unmarshaler interface.
Expand Down
5 changes: 3 additions & 2 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -1596,9 +1596,10 @@ url_file: <filepath>
[ max_alerts: <int> | default = 0 ]
# The maximum time to wait for a webhook request to complete, before failing the
# request and allowing it to be retried.
# request and allowing it to be retried. The default value of 0s indicates that
# no timeout should be applied.
# NOTE: This will have no effect if set higher than the group_interval.
[ timeout: <duration> | default = <none> ]
[ timeout: <duration> | default = 0s ]
```

Expand Down
9 changes: 4 additions & 5 deletions notify/webhook/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
Expand Down Expand Up @@ -113,16 +112,16 @@ func (n *Notifier) Notify(ctx context.Context, alerts ...*types.Alert) (bool, er
url = strings.TrimSpace(string(content))
}

if n.conf.Timeout != nil {
postCtx, cancel := context.WithTimeoutCause(ctx, *n.conf.Timeout, fmt.Errorf("configured webhook timeout (%s) reached", *n.conf.Timeout))
if n.conf.Timeout > 0 {
postCtx, cancel := context.WithTimeoutCause(ctx, n.conf.Timeout, fmt.Errorf("configured webhook timeout reached (%s)", n.conf.Timeout))
defer cancel()
ctx = postCtx
}

resp, err := notify.PostJSON(ctx, n.client, url, &buf)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) && ctx.Err() != nil {
err = context.Cause(ctx)
if ctx.Err() != nil {
err = fmt.Errorf("%w: %w", err, context.Cause(ctx))
}
return true, notify.RedactURL(err)
}
Expand Down

0 comments on commit e731915

Please sign in to comment.