Skip to content

Commit

Permalink
Merge pull request #96 from svix/andor/reconnect-on-error
Browse files Browse the repository at this point in the history
Reconnect to relay after connection interruption
  • Loading branch information
svix-andor committed Mar 23, 2023
2 parents d9aadb4 + 0f75f1d commit 805793c
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion relay/relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -104,14 +105,39 @@ func (c *Client) Listen(ctx context.Context) {
return
}

reconnectBackoffSteps := []time.Duration{
0,
100 * time.Millisecond,
500 * time.Millisecond,
time.Second,
5 * time.Second,
}
reconnectAttempts := 0

for {
err := c.connect(ctx)
if errors.Is(err, context.Canceled) {
c.close()
return
}
if err != nil {
color.Red("Failed to connect to Webhook Relay:\n%s\n", err.Error())
c.close()
return

backoff := reconnectBackoffSteps[len(reconnectBackoffSteps)-1]
if reconnectAttempts < len(reconnectBackoffSteps) {
backoff = reconnectBackoffSteps[reconnectAttempts]
}
color.Yellow("Reattempting connection in %v\n", backoff)
time.Sleep(backoff)

reconnectAttempts += 1
continue
}

// If the connection was successful reset reconnect counter
reconnectAttempts = 0

select {
case <-ctx.Done():
c.stopRead <- Stop{}
Expand Down

0 comments on commit 805793c

Please sign in to comment.