|
| 1 | +package events |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "time" |
| 9 | +) |
| 10 | + |
| 11 | +const ( |
| 12 | + maxRetries = 3 |
| 13 | + retryDelay = 1 * time.Second // Exponentially backed-off: delay will be doubled with each retry |
| 14 | + eventsEndpoint = "http://events.e2b.dev" |
| 15 | +) |
| 16 | + |
| 17 | +type SandboxInternalEvent struct { |
| 18 | + Path string `json:"path"` |
| 19 | + Payload map[string]any `json:"payload"` |
| 20 | +} |
| 21 | + |
| 22 | +func PushEvent(event *SandboxInternalEvent) error { |
| 23 | + var resp *http.Response |
| 24 | + |
| 25 | + jsonData, err := json.Marshal(event.Payload) |
| 26 | + if err != nil { |
| 27 | + return fmt.Errorf("failed to marshal event data: %w", err) |
| 28 | + } |
| 29 | + |
| 30 | + for i := range maxRetries { |
| 31 | + resp, err = makeRequest(event.Path, jsonData) |
| 32 | + if err == nil && resp.StatusCode != http.StatusCreated { |
| 33 | + defer resp.Body.Close() |
| 34 | + if resp.StatusCode == http.StatusTooManyRequests { |
| 35 | + return fmt.Errorf("rate limit exceeded") |
| 36 | + } |
| 37 | + return nil |
| 38 | + } |
| 39 | + |
| 40 | + if resp != nil { |
| 41 | + resp.Body.Close() |
| 42 | + } |
| 43 | + |
| 44 | + if i < maxRetries-1 { |
| 45 | + backoffDelay := retryDelay * time.Duration(1<<uint(i)) |
| 46 | + time.Sleep(backoffDelay) |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + if err != nil { |
| 51 | + return fmt.Errorf("failed to push event after %d retries: %w", maxRetries, err) |
| 52 | + } |
| 53 | + return fmt.Errorf("failed to push event after %d retries: status code %d", maxRetries, resp.StatusCode) |
| 54 | +} |
| 55 | + |
| 56 | +func makeRequest(path string, payload []byte) (*http.Response, error) { |
| 57 | + url := fmt.Sprintf("%s/%s", eventsEndpoint, path) |
| 58 | + return http.Post(url, "application/json", bytes.NewBuffer(payload)) |
| 59 | +} |
0 commit comments