|
| 1 | +// package webhooks provides a webhook manager that can be used to invoke webhooks for different events. |
| 2 | + |
| 3 | +/* |
| 4 | +Usage: |
| 5 | +1. In the caller package (eg, mlp, merlin), define the list of events that requires webhooks. For example: |
| 6 | +
|
| 7 | +```go |
| 8 | +const ( |
| 9 | + ProjectCreatedEvent wh.EventType = "OnProjectCreated" |
| 10 | + ProjectUpdatedEvent wh.EventType = "OnProjectUpdated" |
| 11 | +) |
| 12 | +
|
| 13 | +var EventList = []wh.EventType{ |
| 14 | + ProjectCreatedEvent, |
| 15 | + ProjectUpdatedEvent, |
| 16 | +} |
| 17 | +``` |
| 18 | +
|
| 19 | +2. Define the event to webhook configuration. Optionally, the configuration can be provided in a yaml file |
| 20 | +and parsed via the `Config` struct. |
| 21 | +In the config file, define the event to webhook mapping for those events as required. |
| 22 | +For example, if projects need extra labels from an external source, |
| 23 | +we define the webhook config for the `OnProjectCreated` event |
| 24 | +
|
| 25 | +```go |
| 26 | +webhooks: |
| 27 | + enabled: true |
| 28 | + config: |
| 29 | + OnProjectCreated: |
| 30 | + - url: http://localhost:8081/project_created |
| 31 | + method: POST |
| 32 | + onError: abort |
| 33 | +``` |
| 34 | +
|
| 35 | +3. Call InitializeWebhooks() to get a WebhookManager instance. |
| 36 | + This method will initialize the webhook clients for each event type based on the mapping provided |
| 37 | +
|
| 38 | +```go |
| 39 | +projectsWebhookManager, err := webhooks.InitializeWebhooks(cfg.Webhooks, service.EventList) |
| 40 | +``` |
| 41 | +
|
| 42 | +4. Call `InvokeWebhooks()` method in the caller code based on the event |
| 43 | +*/ |
| 44 | + |
| 45 | +package webhooks |
| 46 | + |
| 47 | +import ( |
| 48 | + "bytes" |
| 49 | + "context" |
| 50 | + "fmt" |
| 51 | + "io" |
| 52 | + "net/http" |
| 53 | + "time" |
| 54 | + |
| 55 | + "github.com/avast/retry-go/v4" |
| 56 | + "github.com/caraml-dev/mlp/api/log" |
| 57 | + "github.com/go-playground/validator/v10" |
| 58 | +) |
| 59 | + |
| 60 | +type EventType string |
| 61 | +type ServiceType string |
| 62 | + |
| 63 | +type WebhookClient interface { |
| 64 | + Invoke(context.Context, []byte) ([]byte, error) |
| 65 | + IsAsync() bool |
| 66 | + IsFinalResponse() bool |
| 67 | + GetUseDataFrom() string |
| 68 | + GetName() string |
| 69 | +} |
| 70 | + |
| 71 | +type simpleWebhookClient struct { |
| 72 | + WebhookConfig |
| 73 | +} |
| 74 | + |
| 75 | +func NoOpErrorHandler(err error) error { return err } |
| 76 | +func NoOpCallback([]byte) error { return nil } |
| 77 | + |
| 78 | +func (g *simpleWebhookClient) Invoke(ctx context.Context, payload []byte) ([]byte, error) { |
| 79 | + // create http request to webhook |
| 80 | + var content []byte |
| 81 | + err := retry.Do( |
| 82 | + func() error { |
| 83 | + client := http.Client{ |
| 84 | + Timeout: time.Duration(*g.Timeout) * time.Second, |
| 85 | + } |
| 86 | + req, err := http.NewRequestWithContext(ctx, g.Method, g.URL, bytes.NewBuffer(payload)) |
| 87 | + // TODO: Add option for authentication headers |
| 88 | + if err != nil { |
| 89 | + return err |
| 90 | + } |
| 91 | + resp, err := client.Do(req) |
| 92 | + if err != nil { |
| 93 | + log.Errorf("Error making client request %s", err) |
| 94 | + return err |
| 95 | + } |
| 96 | + defer resp.Body.Close() |
| 97 | + content, err = io.ReadAll(resp.Body) |
| 98 | + if err != nil { |
| 99 | + return err |
| 100 | + } |
| 101 | + if err := validateWebhookResponse(content); err != nil { |
| 102 | + return err |
| 103 | + } |
| 104 | + // check http status code |
| 105 | + if resp.StatusCode != http.StatusOK { |
| 106 | + return fmt.Errorf("response status code %d not 200", resp.StatusCode) |
| 107 | + } |
| 108 | + return nil |
| 109 | + |
| 110 | + }, retry.Attempts(uint(g.NumRetries)), retry.Context(ctx), |
| 111 | + ) |
| 112 | + if err != nil { |
| 113 | + return nil, err |
| 114 | + } |
| 115 | + return content, nil |
| 116 | +} |
| 117 | + |
| 118 | +func (g *simpleWebhookClient) IsAsync() bool { |
| 119 | + return g.Async |
| 120 | +} |
| 121 | + |
| 122 | +func (g *simpleWebhookClient) IsFinalResponse() bool { |
| 123 | + return g.FinalResponse |
| 124 | +} |
| 125 | + |
| 126 | +func (g *simpleWebhookClient) GetUseDataFrom() string { |
| 127 | + return g.UseDataFrom |
| 128 | +} |
| 129 | + |
| 130 | +func (g *simpleWebhookClient) GetName() string { |
| 131 | + return g.Name |
| 132 | +} |
| 133 | + |
| 134 | +func validateWebhookConfig(webhookConfig *WebhookConfig) error { |
| 135 | + validate := validator.New() |
| 136 | + |
| 137 | + err := validate.Struct(webhookConfig) |
| 138 | + if err != nil { |
| 139 | + return fmt.Errorf("failed to validate configuration: %s", err) |
| 140 | + } |
| 141 | + if webhookConfig.NumRetries < 0 { |
| 142 | + return fmt.Errorf("numRetries must be a non-negative integer") |
| 143 | + } |
| 144 | + return nil |
| 145 | +} |
| 146 | + |
| 147 | +func setDefaults(webhookConfig *WebhookConfig) { |
| 148 | + if webhookConfig.Method == "" { |
| 149 | + webhookConfig.Method = http.MethodPost // Default to POST, TODO: decide if GET is allowed |
| 150 | + } |
| 151 | + if webhookConfig.Timeout == nil { |
| 152 | + def := 10 |
| 153 | + webhookConfig.Timeout = &def |
| 154 | + } |
| 155 | +} |
0 commit comments