fix(event): add 401 handling to prevent infinite retry loop on auth failure
- UploadError struct to distinguish fatal auth errors from network errors - Clear buffer and throttle on 401/403 to save bandwidth - Prevent dead-loop retry when token is invalid or expired
This commit is contained in:
@@ -33,8 +33,15 @@ func (u *Uploader) Run(ctx context.Context) {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case ev := <-u.events:
|
||||
if !u.upload(client, ev) {
|
||||
u.buffer(ev)
|
||||
if err := u.upload(client, ev); err != nil {
|
||||
if ue, ok := err.(*UploadError); ok && ue.Fatal {
|
||||
log.Printf("uploader: FATAL: %s. Clearing buffer and stopping.", ue.Msg)
|
||||
u.buf = nil // Drop all pending events
|
||||
// Give some time before returning or loop with delay
|
||||
time.Sleep(1 * time.Minute)
|
||||
} else {
|
||||
u.buffer(ev)
|
||||
}
|
||||
}
|
||||
case <-ticker.C:
|
||||
u.flushBuffer(client)
|
||||
@@ -53,14 +60,26 @@ func (u *Uploader) buffer(ev SuspectedEvent) {
|
||||
func (u *Uploader) flushBuffer(client *http.Client) {
|
||||
remaining := u.buf[:0]
|
||||
for _, ev := range u.buf {
|
||||
if !u.upload(client, ev) {
|
||||
if err := u.upload(client, ev); err != nil {
|
||||
if ue, ok := err.(*UploadError); ok && ue.Fatal {
|
||||
log.Printf("uploader: FATAL flush: %s. Dropping remaining buffer.", ue.Msg)
|
||||
u.buf = nil
|
||||
return
|
||||
}
|
||||
remaining = append(remaining, ev)
|
||||
}
|
||||
}
|
||||
u.buf = remaining
|
||||
}
|
||||
|
||||
func (u *Uploader) upload(client *http.Client, ev SuspectedEvent) bool {
|
||||
type UploadError struct {
|
||||
Fatal bool
|
||||
Msg string
|
||||
}
|
||||
|
||||
func (e *UploadError) Error() string { return e.Msg }
|
||||
|
||||
func (u *Uploader) upload(client *http.Client, ev SuspectedEvent) error {
|
||||
url := fmt.Sprintf("%s/api/v1/edge/events/suspected", u.cfg.CloudURL)
|
||||
body, _ := json.Marshal(ev)
|
||||
req, _ := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
|
||||
@@ -69,12 +88,18 @@ func (u *Uploader) upload(client *http.Client, ev SuspectedEvent) bool {
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
log.Printf("uploader: upload error: %v", err)
|
||||
return false
|
||||
return nil // Network error, retryable
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
ok := resp.StatusCode == 200 || resp.StatusCode == 201
|
||||
if !ok {
|
||||
log.Printf("uploader: upload failed status=%d", resp.StatusCode)
|
||||
|
||||
if resp.StatusCode == 401 || resp.StatusCode == 403 {
|
||||
return &UploadError{Fatal: true, Msg: fmt.Sprintf("unauthorized (status %d), check token", resp.StatusCode)}
|
||||
}
|
||||
return ok
|
||||
|
||||
if resp.StatusCode == 200 || resp.StatusCode == 201 {
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Printf("uploader: upload failed status=%d", resp.StatusCode)
|
||||
return nil // Server error, retryable
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user